Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support pointer receivers in HaveField; fixes #543 #544

Merged
merged 1 commit into from Apr 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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."))
})
})

})