Skip to content

Commit

Permalink
support pointer receivers in HaveField; fixes onsi#543
Browse files Browse the repository at this point in the history
  • Loading branch information
thediveo committed Apr 17, 2022
1 parent 14c6488 commit 5d3a70b
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
3 changes: 3 additions & 0 deletions matchers/have_field.go
Expand Up @@ -27,6 +27,9 @@ func extractField(actual interface{}, field string) (interface{}, error) {

if strings.HasSuffix(fields[0], "()") {
extractedValue = actualValue.MethodByName(strings.TrimSuffix(fields[0], "()"))
if extractedValue == (reflect.Value{}) && actualValue.CanAddr() {
extractedValue = actualValue.Addr().MethodByName(strings.TrimSuffix(fields[0], "()"))
}
if extractedValue == (reflect.Value{}) {
return nil, fmt.Errorf("HaveField could not find method named '%s' in struct of type %T.", fields[0], actual)
}
Expand Down
30 changes: 30 additions & 0 deletions matchers/have_field_test.go
Expand Up @@ -28,6 +28,14 @@ func (book Book) AbbreviatedAuthor() person {
}
}

func (book Book) ReceiverTitle() string {
return book.Title
}

func (book *Book) PointerReceiverTitle() string {
return book.Title
}

func (book Book) NoReturn() {
}

Expand Down Expand Up @@ -150,4 +158,26 @@ var _ = Describe("HaveField", func() {
Ω(msg).Should(Equal("Value for field 'Title' satisfied matcher, but should not have.\nExpected\n <string>: Les Miserables\nnot to equal\n <string>: Les Miserables"))
})
})

Describe("receiver lookup", func() {
DescribeTable("(pointer) receiver lookup works",
func(field string, expected interface{}) {
Ω(&book).Should(HaveField(field, expected))
},
Entry("non-pointer receiver", "ReceiverTitle()", "Les Miserables"),
Entry("pointer receiver", "PointerReceiverTitle()", "Les Miserables"),
)

It("correctly fails", func() {
matcher := HaveField("ReceiverTitle()", "Les Miserables")
answer := struct{}{}
Ω(matcher.Match(answer)).Error().Should(MatchError(
"HaveField could not find method named 'ReceiverTitle()' in struct of type struct {}."))

matcher = HaveField("PointerReceiverTitle()", "Les Miserables")
Ω(matcher.Match(book)).Error().Should(MatchError(
"HaveField could not find method named 'PointerReceiverTitle()' in struct of type matchers_test.Book."))
})
})

})

0 comments on commit 5d3a70b

Please sign in to comment.