Skip to content

Assertions for Go

Posted November 2017 in #dev

It has long been difficult to write test helpers in Go because you’ve had to keep track of file names and line numbers to exclude helpers from output. This has resulted in some impressive but complicated assertion libraries. Recently, Go 1.9 improved the situation greatly by introducing the Helper method:

The new Helper method, added to both testing.T and testing.B, marks the calling function as a test helper function. When the testing package prints file and line information, it shows the location of the call to a helper function instead of a line in the helper function itself. — The Go Blog

To try this out, I wrote myself a little assertion library. And it’s great! Go can finally have test helpers that tick every box: intuitive signatures, minimal additional complexity, and accurate reporting of file names and line numbers.

package example

import (


func TestExample(t *testing.T) {
	is.Equal(t, 1, 1)
	is.Nil(t, nil)
	is.Zero(t, "")
	is.Error(t, errors.New("error"))

	is.Above(t, 1, 3)
	is.Slice(t, []int{})
	is.Element(t, []int{1, 2, 3}, 3)
	is.Substring(t, "example", "ample")

See the project page for more details.