Getting Started With Testmain in Go
Welcome gophers!
In this tutorial, we’ll be covering how you can use TestMain in order to simplify your tests in Go as well as covering some of the potential drawbacks and caveats to consider when employing this approach.
Video Tutorial
This tutorial is also available in video format:
The TestMain Function
So, the TestMain function is rather special in the sense that, if it is present within a package, it then becomes the main entry point for running the tests within that package.
Why is this potentially beneficial? Well, it allows us to do package-specific test set-up before running through all of the tests.
This can be beneficial in certain circumstances when you want to simplify the tests within your package and focus them specifically on the test case at hand.
Example
Let’s have a look at an example of this in action. Below, you’ll find some tests that feature the TestMain function.
We’ve been able to create a global variable for our resty client which allows our tests to focus purely on the logic around sending HTTP requests to our chosen endpoint and then doing assertions based on the results.
package main
import (
"net/http"
"os"
"testing"
"github.com/go-resty/resty/v2"
)
var (
client *resty.Client
)
func TestMain(m *testing.M) {
client = resty.New()
exitCode := m.Run()
os.Exit(exitCode)
}
func TestHttpBin(t *testing.T) {
t.Run("Testing a get request", func(t *testing.T) {
t.Log("sending get request to https://httpbin.org/get")
resp, err := client.R().Get("https://httpbin.org/get")
if err != nil {
t.Error(err.Error())
}
if resp.StatusCode() != http.StatusOK {
t.Errorf("An unexpected status code has been returned: %d", resp.StatusCode())
}
})
}