Skip to content

Commit

Permalink
Improve message from AssignableToTypeOf when expected value is nil (#281
Browse files Browse the repository at this point in the history
)

* AssignableToTypeOf returns false without error

if exactly one of actual or expected is nil.

Fixes #280.

Signed-off-by: Rowan Jacobs <rojacobs@pivotal.io>

* error when actual is not nil and expected is nil

Signed-off-by: Rowan Jacobs <rojacobs@pivotal.io>
  • Loading branch information
Nick Mahoney authored and blgm committed May 11, 2018
1 parent b7d1a52 commit 9c1fb20
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
6 changes: 5 additions & 1 deletion matchers/assignable_to_type_of_matcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,12 @@ type AssignableToTypeOfMatcher struct {
}

func (matcher *AssignableToTypeOfMatcher) Match(actual interface{}) (success bool, err error) {
if actual == nil || matcher.Expected == nil {
if actual == nil && matcher.Expected == nil {
return false, fmt.Errorf("Refusing to compare <nil> to <nil>.\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.")
} else if matcher.Expected == nil {
return false, fmt.Errorf("Refusing to compare type to <nil>.\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.")
} else if actual == nil {
return false, nil
}

actualType := reflect.TypeOf(actual)
Expand Down
16 changes: 16 additions & 0 deletions matchers/assignable_to_type_of_matcher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,21 @@ var _ = Describe("AssignableToTypeOf", func() {
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})

Context("When actual is nil and expected is not nil", func() {
It("should return false without error", func() {
success, err := (&AssignableToTypeOfMatcher{Expected: 17}).Match(nil)
Expect(success).Should(BeFalse())
Expect(err).ShouldNot(HaveOccurred())
})
})

Context("When actual is not nil and expected is nil", func() {
It("should error", func() {
success, err := (&AssignableToTypeOfMatcher{Expected: nil}).Match(17)
Expect(success).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})
})
})
})

0 comments on commit 9c1fb20

Please sign in to comment.