5 years later, a new way to test in Go

5 years ago I forked https://github.com/stretchr/testify, because I wanted to "fix" the ordering of arguments to some of the functions. It isn't something that really matters, as I've lived with it for 5 years and it is one of the more popular assertion packages.

But last week I started thinking about it again, and decided that maybe I should do something about:


assert.Equal(t, expected, actual)
assert.Len(t, actualList, expectedLength)

As I'd already published the package, by virtue of having my fork on GitHub, I didn't want to change the existing API. I doubt anyone else relied on it, and with modules it shouldn't affect me, but I am trying to do things at least semi-properly.

So I added a new API. The new style is impossible to get wrong. The only cost is that you have to get the assertion function by wrapping the *testing.T first (you don't have to, but it would be ugly not to).

assert := assert.Wrap(t)

assert(actual).Equal(expected)
assert(actualList).Len(expectedLength)

I haven't changed the naming so some of them may read a bit weird.

When I originally forked the repo I did do one thing: I moved the assert package to be the root. I never really liked the style of test where the first failing assertion quits the test. It just means you have to run a test over and over to find all of the problems. But sometimes it is useful if one assertion means the others are pointless; for instance, if a list is empty you don't need to assert properties on the first element.

With the new API I have been able to provide the ability to do both. Using the .Must property on the wrapped assertion function gives access to the same API but with the methods will terminate the current test.

assert := assert.Wrap(t)

assert(actual).Must.Equal(expected)
assert(actualList).Must.Len(expectedLength)

Admittedly the naming does get even more off with the word "Must" in the middle, but this is Go not English…

Anyway a 5 year long task, done.

article published
using tally-ho-local
Interactions (0)