Test setup and teardown
We’ve written our first example of a test and source code by leveraging an external test package and the testing.T
type. This has worked very well for our simple example, but, as we begin to ramp up and write more tests, it can be cumbersome to continue repeating the same test setup and cleanup. In this section, we will explore what functionality the testing
package offers to streamline this process for us.
The TestMain approach
Go 1.4 introduced a new special test called TestMain
. This is a feature that is often underutilized, but it gives us great flexibility when it comes to setup and teardown code. The signature of this test is as follows:
func TestMain(m *testing.M) { // implementation }
Unlike other tests, the name of this test is fixed and it takes in the *testing.M
type as its only parameter, as opposed to *testing.T
as other tests do. Once you override it, the code in this method will give you more control over how your...