English
Go Unit Testing in Practice: Testify Assertions and Instance Lifecycle Verification

1. Introduction
In Go development, unit testing is about more than simply checking whether a function executes successfully. More importantly, it verifies whether the application behaves as expected.
When developing infrastructure components, we often need to test several things:
- Whether configuration is loaded correctly.
- Whether clients such as Redis and Etcd are initialized successfully.
- Whether a Factory can create components correctly.
- Whether an SDK reuses instances as expected.
- Whether different components share the correct instances.
- Whether infrastructure services are actually available.
These scenarios involve object initialization, instance reuse, object identity, and interactions with real infrastructure services.
This article uses github.com/stretchr/testify and examples from a real Go project involving Store, Factory, and EtcdSDK components to explore commonly used assertions and their practical applications.
We will start with basic assertions and gradually move toward object identity verification and infrastructure component lifecycle testing.
2. Common Testify Assertions
testify is one of the most widely used testing libraries in the Go ecosystem. It provides several useful packages, including assert, require, and suite.
2.1 NotNil: Verify That an Object Is Not Nil
go
assert.NotNil(t, client)NotNil verifies that an object is not nil.
Typical use cases include:
- Verifying that a client has been initialized.
- Checking that a component returned by a Factory is not nil.
- Confirming that an SDK object has been created.
For example:
go
func (suite *StoreSuite) Test_Etcd() {
assert.NotNil(suite.T(), suite.factory.Etcd())
}However, NotNil only proves that the object is not nil. It does not prove that the underlying service is connected or available.
For example, an Etcd client may use lazy connection behavior. The client can be created successfully even when the Etcd service is not running.
Therefore, successful object initialization and successful infrastructure connectivity are two different testing objectives.
2.2 NoError: Verify That an Operation Returns No Error
go
assert.NoError(t, err)NoError verifies that a function returns no error.
For example:
go
client, err := NewClient()
assert.NoError(t, err)
assert.NotNil(t, client)During test setup, however, it is often better to use require when subsequent operations depend on the result:
go
require.NoError(t, err)
require.NotNil(t, client)The main difference is how they behave when an assertion fails:
| Assertion | Behavior on failure |
|---|---|
assert.NoError | Marks the test as failed but continues execution |
require.NoError | Marks the test as failed and immediately stops the current test |
In practice:
- Use
assertwhen you want to collect multiple independent assertion failures in one test. - Use
requirewhen subsequent operations depend on the current result.
2.3 Equal: Verify That Two Values Are Equal
go
assert.Equal(t, expected, actual)Equal compares two values and verifies that they are equal.
For example:
go
expected := "127.0.0.1:2379"
actual := config.Database.Etcd.Hosts[0]
assert.Equal(t, expected, actual)Typical use cases include:
- Configuration validation.
- Comparing strings, numbers, and struct fields.
- Verifying function return values.
- Checking data transformation results.
It is important to understand that Equal compares values, not whether two variables refer to the same object instance.
2.4 Same: Verify That Two Variables Refer to the Same Instance
This is particularly useful when testing infrastructure components.
go
assert.Same(t, first, second)Same verifies whether two pointers refer to the exact same object.
For example:
go
first := suite.factory.EtcdSDK()
second := suite.factory.EtcdSDK()
assert.Same(suite.T(), first, second)If the Factory is designed to reuse a singleton instance, both calls should return the same instance.
This assertion verifies more than whether an object exists. It verifies whether the instance is actually reused.
Equal vs. Same
Consider the following example:
go
type Client struct {
Name string
}
first := &Client{Name: "etcd"}
second := &Client{Name: "etcd"}In this case, both assertions pass:
go
assert.Equal(t, first, second)
assert.NotSame(t, first, second)Why?
Equal: The contents of the two objects are equal.NotSame: The two pointers do not refer to the same object.
Now consider:
go
second := first
assert.Equal(t, first, second)
assert.Same(t, first, second)Both assertions also pass, but they verify different properties.
When testing singleton behavior in a Factory, use Same rather than relying only on Equal.
2.5 NotSame: Verify That Two Instances Are Independent
go
assert.NotSame(t, first, second)NotSame is the opposite of Same. It verifies that two objects are not the same instance.
Typical use cases include:
- Verifying that a Factory creates independent instances on each call.
- Checking that different configurations produce different clients.
- Ensuring that objects are not unintentionally shared.
For example:
go
first := NewClient(configA)
second := NewClient(configB)
assert.NotSame(t, first, second)Note that NotSame only verifies object identity. It does not guarantee that the business data stored in the two objects is different.
3. Real-World Project Context: Store and Factory
In real-world Go projects, infrastructure components are often encapsulated in a Store layer and exposed through a unified Factory.
For example, in our project, the Store manages the following infrastructure components:
- Etcd: A distributed configuration and data storage component.
- EtcdSDK: A business-oriented SDK built on top of Etcd.
- QueueClient: A message queue client.
To prevent business modules from depending directly on low-level infrastructure clients, we use a Factory to centralize component creation and access.
3.1 Component Architecture
The overall component relationship looks like this:
With this design, we need to verify not only whether the Factory can create components, but also whether their instance lifecycles behave as expected.
Our tests therefore focus on three aspects:
- Whether infrastructure components can be initialized successfully.
- Whether the Factory provides the expected components.
- Whether components that should be reused return the same instance across multiple calls.
3.2 Test Environment Initialization
The project uses testify/suite to organize tests. We use SetupTest() to initialize the test environment before each test method.
The setup process includes:
- Locating the project configuration directory.
- Loading the project configuration.
- Initializing the Etcd client.
- Creating the Store Factory.
Here is the actual project code:
go
func TestEtcdSuite(t *testing.T) {
suite.Run(t, &StoreSuite{})
}
type StoreSuite struct {
suite.Suite
configure *config.Configure
factory Factory
ctx context.Context
baseDir string
configDir string
}The SetupTest() implementation:
go
func (s *StoreSuite) SetupTest() {
s.baseDir = "./../"
s.configDir = fsx.MustGetFilePathWithFileSystemPath(
s.baseDir,
fsx.WithSpecificFileSystemPath("etc"),
)
require.NotEmpty(s.T(), s.configDir)
require.Contains(s.T(), s.configDir, "/etc")
name := filename.GetFilename(
s.configDir,
filename.WithServerRunningMode(config.DefaultRunningMode),
)
s.ctx = context.Background()
var err error
s.configure, err = config.GetConfigure(
configure.WithReceiver(config.NewConfigureDefault()),
configure.WithFilename(name),
)
require.NoError(s.T(), err)
require.NotNil(s.T(), s.configure)
clientOr, err := etcdc.NewClientOr(
s.configure.Database.Etcd.Hosts,
)
require.NoError(s.T(), err)
require.NotNil(s.T(), clientOr)
s.factory = NewFactory(s.configure, clientOr)
require.NotNil(s.T(), s.factory)
}We use require instead of assert because the remaining test operations depend on successful initialization of the configuration, Etcd client, and Factory.
If initialization fails, there is no reason to continue executing the current test.
One important detail: a successful return from NewClientOr() only indicates that the client creation process did not return an error. It does not prove that the Etcd service is healthy. Actual connectivity must be verified through an Etcd operation or a health check.
3.3 SetupTest Execution Flow
SetupTest() is executed before every test method in the Suite.
This means the initialization process runs again for each test method.
Consequently, the two calls inside Test_EtcdSDK happen within the same test execution and use the same Factory instance. They do not share an instance across different test methods.
4. Real-World Test Cases
With the test environment in place, we can test each component provided by the Factory.
4.1 Case 1: Etcd Component Initialization
Actual code:
go
func (s *StoreSuite) Test_Etcd() {
assert.NotNil(s.T(), s.factory.Etcd())
}Test objective:
Verify that the Factory can provide an Etcd component.
Here, assert.NotNil() checks whether the object has been initialized.
It does not verify whether the Etcd service is actually available, nor does it verify whether multiple calls return the same instance.
4.2 Case 2: EtcdSDK Singleton Instance Verification
Actual code:
go
func (s *StoreSuite) Test_EtcdSDK() {
first := s.factory.EtcdSDK()
second := s.factory.EtcdSDK()
assert.NotNil(s.T(), first)
assert.Same(s.T(), first, second)
}This is the most interesting test case in this article.
We call the Factory twice:
go
first := s.factory.EtcdSDK()
second := s.factory.EtcdSDK()Then we use:
go
assert.Same(s.T(), first, second)to verify whether both calls return the same instance.
This is not simply a comparison of object values. It verifies that both references have the same object identity.
Why this test matters:
- It verifies whether the SDK is reused as designed.
- It helps prevent unnecessary SDK instance creation.
- It validates the Factory's instance lifecycle management.
Keep in mind that Same only verifies that these two calls return the same instance. It does not independently prove that the Factory is safe under concurrent access. Concurrency safety requires additional tests.
4.3 Case 3: QueueClient Initialization
Actual code:
go
func (s *StoreSuite) Test_QueueClient() {
assert.NotNil(s.T(), s.factory.QueueClient())
}Test objective:
Verify that the Factory can provide a QueueClient.
The current test only covers client object initialization. It does not verify connectivity to a Redis or message queue service, nor does it establish that QueueClient is intended to behave as a singleton.
If we later need to verify connection pooling, queue operations, or message delivery, we can add separate integration tests.
4.4 Test Coverage Summary
| Test Case | What It Verifies | Assertion |
|---|---|---|
| Test_Etcd | Etcd object initialization | NotNil |
| Test_EtcdSDK | SDK object initialization | NotNil |
| Test_EtcdSDK | SDK instance reuse | Same |
| Test_QueueClient | QueueClient object initialization | NotNil |
These test cases extend basic nil checks to include Factory instance identity verification.
4.5 Same and NotSame: Object Identity Verification
If we want to verify that two instances are independent, we can use:
go
assert.NotSame(suite.T(), first, second)The key point is that assertions should follow the component's intended lifecycle contract.
- If an SDK is designed as a singleton, use
Same. - If a component is designed to create a new instance on every call, use
NotSame.
Do not choose an assertion simply because it makes the test pass.
5. Object Initialization vs. Actual Service Connectivity
This is one of the most common misunderstandings when testing infrastructure components.
Consider the following code:
go
client, err := etcdc.NewClientOr(hosts)
require.NoError(t, err)
require.NotNil(t, client)This only proves that the client was created successfully.
It does not prove that the Etcd service is actually available.
Real infrastructure connectivity should be tested separately through health checks.
5.1 Etcd Health Check
Using the official Etcd Go client as an example, we can verify whether an endpoint is available through Status():
go
ctx, cancel := context.WithTimeout(
context.Background(),
5*time.Second,
)
defer cancel()
_, err := client.Status(ctx, endpoint)
require.NoError(t, err)The client and endpoint values should be obtained from the actual project implementation.
5.2 Redis Health Check
Redis follows the same principle:
go
ctx, cancel := context.WithTimeout(
context.Background(),
5*time.Second,
)
defer cancel()
err := redisClient.Ping(ctx).Err()
require.NoError(t, err)5.3 Separating Testing Layers
We recommend dividing tests into three layers:
| Testing Layer | Objective |
|---|---|
| Initialization tests | Verify that objects can be created |
| Instance tests | Verify object identity and lifecycle |
| Integration tests | Verify real infrastructure services and operations |
This separation prevents us from treating successful client initialization as proof of successful service connectivity.
It also avoids making every ordinary unit test depend on external services such as Redis or Etcd.
Interfaces and mocks can isolate unit tests, while dedicated integration tests can validate real infrastructure behavior.
6. Going Further: Factory Concurrency Safety
Our previous Same test verifies instance reuse when the same Factory instance is called sequentially.
However, if a Factory is accessed by multiple Goroutines, we also need to consider concurrent initialization.
For example:
go
func (s *StoreSuite) Test_EtcdSDK_Concurrent() {
const workers = 10
instances := make([]*EtcdSDK, workers)
var wg sync.WaitGroup
for i := range workers {
wg.Add(1)
go func(i int) {
defer wg.Done()
instances[i] = s.factory.EtcdSDK()
}(i)
}
wg.Wait()
for i := range instances {
require.NotNil(s.T(), instances[i])
assert.Same(s.T(), instances[0], instances[i])
}
}This example assumes that EtcdSDK() returns *EtcdSDK. The actual type should match the project's implementation.
The test verifies whether multiple Goroutines calling the Factory concurrently eventually receive the same SDK instance.
If the Factory uses mechanisms such as sync.Once or mutexes to ensure safe initialization, this test can help verify the expected behavior.
We can also run:
bash
go test -race ./...to detect data races during concurrent access.
Keep in mind that a concurrency test cannot prove the absence of every possible race condition. The Race Detector can only identify data races exposed by the execution paths exercised during testing.
7. Testify Assertion Quick Reference
| Assertion | What It Verifies | Typical Use Case |
|---|---|---|
| NotNil | Object is not nil | Client initialization |
| Nil | Object is nil | Optional object validation |
| NoError | No error occurred | Function execution |
| Error | An error occurred | Error handling |
| Equal | Values are equal | Configuration and results |
| NotEqual | Values are different | State changes |
| Same | Same object instance | Singleton reuse |
| NotSame | Different object instances | Independent objects |
| True | Condition is true | Boolean state |
| False | Condition is false | Boolean state |
| Contains | Contains expected content | Strings and collections |
| Empty | Content is empty | Empty collection validation |
| NotEmpty | Content is not empty | Configuration and results |
| Len | Expected length | Slices and maps |
| Panics | Execution causes a panic | Panic handling |
| NotPanics | Execution does not panic | Stability verification |
8. Engineering Best Practices
Based on our infrastructure testing experience, the following practices are worth adopting.
8.1 Separate Object Initialization from Service Availability
NotNil is not a replacement for a health check.
Successfully creating a client object does not mean that the underlying Redis or Etcd service is available.
8.2 Distinguish Value Equality from Object Identity
Use Same when verifying singleton reuse, and NotSame when verifying independent instances.
This distinction is particularly important when testing Factory lifecycle behavior.
8.3 Use assert and require Appropriately
Prefer require during initialization to prevent subsequent operations from running after a critical setup failure.
Use assert when you want to validate multiple independent conditions in a single test.
8.4 Test Object Lifecycle Contracts
A Factory should be tested not only for its ability to create objects, but also for whether those objects are reused or independently created as designed.
8.5 Separate Unit Tests from Integration Tests
Ordinary unit tests should not all depend on external services such as Redis or Etcd.
Use interfaces and mocks to isolate unit tests, while maintaining dedicated integration tests for real infrastructure interactions.
8.6 Pay Attention to Concurrent Access
For Factories that may be accessed by multiple Goroutines, verify whether initialization and instance reuse are concurrency-safe.
Combine concurrency tests with go test -race to detect potential data races.
9. Conclusion
The value of Go unit testing goes beyond verifying function results. It also helps validate the constraints and contracts defined by the software design.
For infrastructure components in particular:
NotNilverifies that an object exists.NoErrorverifies that an operation succeeds.Equalverifies that object values match expectations.Sameverifies that the same instance is reused.NotSameverifies that separate instances are created.- Health checks verify that the underlying infrastructure is actually available.
Among these assertions, Same and NotSame deserve special attention.
They allow us to move beyond traditional result-based testing and verify object identity and lifecycle behavior.
Starting with Etcd, EtcdSDK, and QueueClient in a real project, we can gradually build a testing strategy that covers object initialization, instance reuse, concurrency safety, and real infrastructure interactions.
Good unit tests do more than prove that code runs. They prove that code runs according to its design.