From 92af479c56399dd7038c9ae6754cb30d5a039532 Mon Sep 17 00:00:00 2001 From: Steve Leonard Date: Sat, 15 Feb 2014 12:24:39 -0500 Subject: [PATCH] ExactError, asserts that err is not nil and its string matches --- assert/assertions.go | 19 +++++++++++++++++++ assert/assertions_test.go | 16 ++++++++++++++++ assert/errors.go | 2 +- 3 files changed, 36 insertions(+), 1 deletion(-) diff --git a/assert/assertions.go b/assert/assertions.go index 5165cd2..df39576 100644 --- a/assert/assertions.go +++ b/assert/assertions.go @@ -469,3 +469,22 @@ func Error(t TestingT, theError error, msgAndArgs ...interface{}) bool { return NotNil(t, theError, "An error is expected but got nil. %s", message) } + +// Error asserts that a function returned an error (i.e. not `nil`). +// +// actualObj, err := SomeFunction() +// if assert.Error(t, err, "An error was expected") { +// assert.Equal(t, err, expectedError) +// } +// +// Returns whether the assertion was successful (true) or not (false). +func ExactError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool { + + message := messageFromMsgAndArgs(msgAndArgs...) + if !NotNil(t, theError, "An error is expected but got nil. %s", message) { + return false + } + s := "An error with value \"%s\" is expected but got \"%s\". %s" + return Equal(t, theError.Error(), errString, + s, errString, theError.Error(), message) +} diff --git a/assert/assertions_test.go b/assert/assertions_test.go index 648d76e..b6a13de 100644 --- a/assert/assertions_test.go +++ b/assert/assertions_test.go @@ -311,6 +311,22 @@ func TestError(t *testing.T) { } +func TestExactError(t *testing.T) { + mockT := new(testing.T) + + // start with a nil error + var err error = nil + False(t, ExactError(mockT, err, ""), + "ExactError should return false for nil arg") + + // now set an error + err = errors.New("Some error") + False(t, ExactError(mockT, err, "Not some error"), + "ExactError should return false for different error string") + True(t, ExactError(mockT, err, "Some error"), + "ExactError should return true") +} + func Test_isEmpty(t *testing.T) { True(t, isEmpty("")) diff --git a/assert/errors.go b/assert/errors.go index fa2e393..da004d1 100644 --- a/assert/errors.go +++ b/assert/errors.go @@ -4,7 +4,7 @@ import ( "errors" ) -// AnError is an erorr instance useful for testing. If the code does not care +// AnError is an error instance useful for testing. If the code does not care // about error specifics, and only needs to return the error for example, this // error should be used to make the test code more readable. var AnError error = errors.New("assert.AnError general error for testing.")