For complex testing, the testify module
is a big life saver, it has 4 main packages: assert, require, mock and suite.
Their usages are quite straightforward from the testify
README file.
There is a series of tutorial about how to use testify, pretty helpful.
Here in this blog I highlight the parts that are important to me.
Mock Objects Generation
Regarding mock
, to create mocking objects for external dependencies, we use
mockery
to
generate mock objects from go interface
.
Thus to write testable code in Go, thinking about how to use interface properly.
Install mockery binary:
1 | # Check current release tag and use it |
Mock objects generation command:
1 | # If you are using mockery binary downloaded, run it from the repo with absolute |
Other flags please see mockery --help
.
Or using docker:
1 | docker run --rm -v $(pwd):/src \ |
Then in your test go file, import the mocks
package and use it.
Suite
The suite helps the testing lifecycle management, for example, it provides setup/teardown stage for test cases.
For example the basic suite structure:
1 | import ( |
The commonly used assertions:
1 | s.Require().Nil(err) |
Run Test
To run suite, using the same go test
command:
1 | # To run the whole package test suites |