Skip to content

Commit e01e5a8

Browse files
committed
Use reflection for nil error comparison
1 parent 009470e commit e01e5a8

File tree

3 files changed

+11
-6
lines changed

3 files changed

+11
-6
lines changed

.travis.yml

-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ go:
88
- 1.9
99
- "1.10"
1010
- 1.11
11-
- tip
1211

1312
env: GO15VENDOREXPERIMENT=1
1413
script: go test -v ./...

assert/error.go

+6-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package assert
22

3+
import "reflect"
4+
35
// AssertableError represents an under-test error that's expected to meet
46
// certain criteria.
57
type AssertableError interface {
@@ -34,7 +36,8 @@ func (err ErrorString) Error() string {
3436
}
3537

3638
func (actual *assertableError) Equals(expected error) ValueAssertionResult {
37-
if expected == nil {
39+
// Allow reflect to check for nil expected error as that object could have been loaded from JSON file (for DDT)
40+
if expected == nil || (reflect.ValueOf(expected).Kind() == reflect.Ptr && reflect.ValueOf(expected).IsNil()) {
3841
return actual.IsNil()
3942
}
4043
if actual.value == nil {
@@ -50,14 +53,14 @@ func (actual *assertableError) Equals(expected error) ValueAssertionResult {
5053
}
5154

5255
func (actual *assertableError) IsNil() ValueAssertionResult {
53-
if actual.value != nil {
56+
if actual.value != nil { // no reflection here as we want to verify that the interface itself is not nil
5457
actual.testContext.decoratedErrorf("Actual error was not <nil>.\nActual: %v\n", actual.value)
5558
}
5659
return &valueAssertionResult{bool: actual.value == nil, actual: actual.value, expected: nil}
5760
}
5861

5962
func (actual *assertableError) IsNotNil() ValueAssertionResult {
60-
if actual.value == nil {
63+
if actual.value == nil { // no reflection here as we want to verify that the interface itself is nil
6164
actual.testContext.decoratedErrorf("Actual error was <nil>.\n")
6265
}
6366
return &valueAssertionResult{bool: actual.value != nil, actual: actual.value, expected: &anyOtherValue{}}

assert/error_test.go

+5-2
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,14 @@ import (
66
)
77

88
func ExampleAssertableError_Equals_pass() {
9+
var nilError *ErrorString
910
cases := []struct {
1011
id string
1112
actual error
1213
expected error
1314
}{
14-
{"both are nil", nil, nil},
15+
{"nil interfaces", nil, nil},
16+
{"nil interface and nil pointer", nil, nilError},
1517
{"same type and message", errors.New("foo"), errors.New("foo")},
1618
{"different struct types, same message", ErrorString("foo"), errors.New("foo")},
1719
}
@@ -22,7 +24,8 @@ func ExampleAssertableError_Equals_pass() {
2224
}
2325
}
2426
// Output:
25-
// Passed: both are nil
27+
// Passed: nil interfaces
28+
// Passed: nil interface and nil pointer
2629
// Passed: same type and message
2730
// Passed: different struct types, same message
2831
}

0 commit comments

Comments
 (0)