0
0
GoHow-ToBeginner · 4 min read

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.T as the first argument to assertion functions.
  • Confusing the order of expected and actual values in assertions.
  • Forgetting to import the assert package.

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

FunctionPurposeExample Usage
assert.EqualCheck if two values are equalassert.Equal(t, expected, actual)
assert.NotNilCheck if value is not nilassert.NotNil(t, object)
assert.TrueCheck if condition is trueassert.True(t, condition)
assert.NilCheck if value is nilassert.Nil(t, object)
assert.ErrorCheck if error is not nilassert.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.