How to Use Testify in Go for Easy Testing
To use
testify in Go, first install it with go get github.com/stretchr/testify. Then import testify/assert in your test files to use helpful assertion functions like assert.Equal for easy test checks.Syntax
The basic syntax to use Testify's assertions in Go tests involves importing the assert package and calling assertion functions inside your test functions.
assert.Equal(t, expected, actual): Checks if two values are equal.assert.NotNil(t, object): Checks if an object is not nil.assert.True(t, condition): Checks if a condition is true.
Each assertion takes t *testing.T as the first argument to report failures.
go
import ( "testing" "github.com/stretchr/testify/assert" ) func TestSomething(t *testing.T) { var expectedValue = 42 var actualValue = 42 assert.Equal(t, expectedValue, actualValue, "Values should be equal") }
Example
This example shows how to write a simple test using Testify's assert package to check if a function returns the expected result.
go
package main import ( "testing" "github.com/stretchr/testify/assert" ) func Add(a, b int) int { return a + b } func TestAdd(t *testing.T) { sum := Add(2, 3) assert.Equal(t, 5, sum, "Add(2, 3) should be 5") }
Output
PASS
ok command-line-arguments 0.001s
Common Pitfalls
Common mistakes when using Testify include:
- Not passing
t *testing.Tas the first argument to assertion functions. - Confusing the order of
expectedandactualvalues in assertions. - Forgetting to import the
assertpackage.
Here is an example of a wrong and right usage:
go
func TestWrong(t *testing.T) {
// Wrong: missing t argument
// assert.Equal(5, Add(2, 3)) // This will not compile
// Wrong: swapped expected and actual
assert.Equal(t, Add(2, 3), 5, "Swapped args") // This works but message may confuse
// Right:
assert.Equal(t, 5, Add(2, 3), "Correct usage")
}Quick Reference
| Function | Purpose | Example Usage |
|---|---|---|
| assert.Equal | Check if two values are equal | assert.Equal(t, expected, actual) |
| assert.NotNil | Check if value is not nil | assert.NotNil(t, object) |
| assert.True | Check if condition is true | assert.True(t, condition) |
| assert.Nil | Check if value is nil | assert.Nil(t, object) |
| assert.Error | Check if error is not nil | assert.Error(t, err) |
Key Takeaways
Install Testify with 'go get github.com/stretchr/testify' before using it.
Import 'github.com/stretchr/testify/assert' to access assertion functions.
Always pass '*testing.T' as the first argument to assertion functions.
Use 'assert.Equal(t, expected, actual)' to compare values clearly.
Avoid swapping expected and actual arguments to prevent confusing test results.