Skip to content
On this page

Unit Testing

Base on stretchr/testify: A toolkit with common assertions and mocks that plays nicely with the standard library (github.com)

Getting Started with Testify

Testify is a popular testing framework for Go that provides a set of utilities and assertions to simplify unit testing. This guide will help you get started with Testify and show you how to write effective tests for your Go projects.

Installation

To start using Testify, you need to install it first. Open your terminal and run the following command:

shell
go get github.com/stretchr/testify

This command will download and install Testify along with its dependencies into your Go workspace.

Writing Your First Test

Once Testify is installed, you can begin writing tests using its expressive and powerful assertion library. Let's start by creating a new Go file named my_test.go in your project directory.

go
package mypackage_test

import (
	"testing"
	"github.com/stretchr/testify/assert"
)

func TestAddition(t *testing.T) {
	result := 2 + 2
	expected := 4

	assert.Equal(t, expected, result, "The result should be 4.")
}

In this example, we import the testing package as usual, but we also import the github.com/stretchr/testify/assert package to gain access to Testify's assertion functions.

The TestAddition function is a test function that will be executed by the go test command. Inside this function, we perform an addition operation and use the assert.Equal function to check if the result matches the expected value.

Running the Test

To run the test, navigate to the directory containing your test file (my_test.go) in the terminal and execute the following command:

shell
go test

Go will execute all the test functions in the file and display the test results.

Advanced Assertions and Utilities

Testify provides a wide range of assertion functions and utility methods to help you write comprehensive tests. Some of the commonly used functions include:

  • assert.Equal: Checks if two values are equal.
  • assert.NotNil: Checks if a value is not nil.
  • assert.Contains: Checks if a substring is present in a given string.
  • assert.Len: Checks the length of a collection.

Refer to the Testify documentation for a complete list of available assertions and utilities.

Conclusion

You've successfully set up Testify and written your first test using the framework. Testify's assertion library and utilities will enable you to write expressive, readable, and effective tests for your Go projects. Explore the official documentation and experiment with more advanced features to enhance your testing experience.

Happy testing!

Maintained by Passakon Puttasuwan & Dev Core Team.