Golang: Testify Require vs Assert

It may be confusing why testify includes two copies of the assertion API: require and assert. The behave differently: require will halt the test and fail, while assert will not stop execution of the test. require is likely the behaviour you expect, but assert is a great tool if you’re trying to check several result conditions at once. Here is an example to help demonstrate:

// […] assume a user og exists, and we are testing an update
got, err := getUser(og.id)

// halt execution if we get an error
require.Nil(err)

// check all assertions
assert.Equal(og.id, got.id, “id should not change”)
assert.Equal(newNname, got.name, “name should be the new name”)
assert.Equal(og.created, got.created, “created date should never change.”)
assert.GreaterOrEqual(og.modified, got.modified, “modified date is updated on save.”)

If an error is returned from getUser, execution will halt. But if any of the assertions fail, all of the assertions will still be checked. This lets you get all of the assertion issues at once without needing to fix and re-run the tests. I’ve never seen a toolkit like this in another language, but it makes sense.

Subscribe to our newsletter and receive our very latest news.

Go back

Your message has been sent

Warning
Warning
Warning.

Leave a comment