Testify require and assert: Difference between revisions
Jump to navigation
Jump to search
Line 5: | Line 5: | ||
=Overview= | =Overview= | ||
=Equality and Non-Equality= | =Equality and Non-Equality= | ||
In case the result is failure, <code>Equal()</code> and <code>NotEqual()</code> delegate to <code>Fail()</code>. | |||
<syntaxhighlight lang='go'> | |||
package somepkg | |||
import ( | |||
"testing" | |||
testifyassert "github.com/stretchr/testify/assert" | |||
) | |||
func TestSomething(t *testing.T) { | |||
assert := testifyassert.New(t) | |||
assert.Equal(123, 123, "this message is displayed when the test fails %s", "because of inequality") | |||
assert.NotEqual(123, 123, "this message is displayed when the test fails %s", "because of equality") | |||
} | |||
</syntaxhighlight> | |||
=Nil and Non-Nil= | =Nil and Non-Nil= |
Revision as of 00:59, 12 March 2024
External
Internal
Overview
Equality and Non-Equality
In case the result is failure, Equal()
and NotEqual()
delegate to Fail()
.
package somepkg
import (
"testing"
testifyassert "github.com/stretchr/testify/assert"
)
func TestSomething(t *testing.T) {
assert := testifyassert.New(t)
assert.Equal(123, 123, "this message is displayed when the test fails %s", "because of inequality")
assert.NotEqual(123, 123, "this message is displayed when the test fails %s", "because of equality")
}
Nil and Non-Nil
Failing the Test
Failing a Test from a Goroutine
package yours
import (
"testing"
tassert "github.com/stretchr/testify/assert"
)
func TestSomething(t *testing.T) {
assert := tassert.New(t)
// assert equality
assert.Equal(123, 123, "they should be equal")
// assert inequality
assert.NotEqual(123, 456, "they should not be equal")
// assert for nil (good for errors)
assert.Nil(object)
// assert for not nil (good when you expect something)
if assert.NotNil(object) {
// now we know that object isn't nil, we are safe to make
// further assertions without causing any errors
assert.Equal("Something", object.Value)
}
}
To check that an error has the expected message:
err := ...
assert.NotNil(err)
assert.Equal(err.Error(), "expected message")