From 8dab36e62ea11209b9bc86933056df05cf9f3e67 Mon Sep 17 00:00:00 2001 From: TheDiveO <6920158+thediveo@users.noreply.github.com> Date: Tue, 19 Apr 2022 16:54:16 +0200 Subject: [PATCH] support pointer receivers in HaveField; fixes #543 (#544) --- matchers/have_field.go | 3 +++ matchers/have_field_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/matchers/have_field.go b/matchers/have_field.go index e1fe934d5..0ff4670d9 100644 --- a/matchers/have_field.go +++ b/matchers/have_field.go @@ -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) } diff --git a/matchers/have_field_test.go b/matchers/have_field_test.go index 0506600b9..c49bc8041 100644 --- a/matchers/have_field_test.go +++ b/matchers/have_field_test.go @@ -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() { } @@ -150,4 +158,26 @@ var _ = Describe("HaveField", func() { Ω(msg).Should(Equal("Value for field 'Title' satisfied matcher, but should not have.\nExpected\n : Les Miserables\nnot to equal\n : 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.")) + }) + }) + })