Learn to Code via Tutorials on Repl.it!

← Back to all posts
Testing in Go

Go testing support is awesome. It has a subcommand go test that looks for *_test.go files in package folder and run all test functions that starts with Test* prefix and report success or error.

All test functions should follow this naming convention

t param is used to report success/failure messages. Some useful methods are

More on testing package are here

Say, we have a package hello that defines a simple Hello function as follows that we want to add test

We need to create hello_test.go file in same directory

Now we have tests for our hello package. To test we need go to the folder hello/

If we do go test it will run the test runner and execute all Test* functions and report success/error

To see which tests were run we can use verbose option go test -v

We can also specify a substring of specific test function go test -v -run="Hello" and test runner will look for test functions that uses the substring

Table driven Testing

Now we added a Greet function that takes a param and return a greet message

Now we want to test Greet function but with different test cases, we can create a slice of struct with input, output definition and check results in a loop. This is called table driven testing.

Here we uses an anonymous struct that has testDest, input and output fields, and then we create a slice of struct with our test cases.
t.Run takes an anynymous function which is similar to our TestHello function.

Go does not provide any built assertion library but there are plenty out there to import. one is testify/assert

Once we import it from github.com/stretchr/testify/assert we can use differnt assertion functions like these

Now we can run tests against this test as go test -v -run="Greet"