#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())
}
})
}
Conclusion
TestMain is a powerful feature in Go that allows you to set up and tear down resources for your entire test suite. This can be particularly useful when working with external dependencies or when you need to initialize complex test fixtures.
If you’re looking to expand your testing knowledge, check out our other testing resources like Getting Started With Go for the basics, or explore more advanced Go patterns for structuring your applications effectively.
Continue Learning
Go 1.23 Iterators Tutorial
In this tutorial, we'll be exploring the new range-over-func syntax introduced in Go 1.23 and how to use iterators in your Go applications.
Functional Options Parameter Pattern in Go
In this tutorial, we'll be discussing one of my favorite patterns and how you can use it to supercharge your Go app dev.
Joining Errors With errors.Join in Go
In this tutorial, we'll be looking at how we can join errors together in Go using the errors.Join method!
Creating a RESTful API With Golang
this tutorial demonstrates how you can create your own simple RESTful JSON api using Go(Lang)