Skip to content

Commit 4feb9d7

Browse files
thediveoonsi
authored andcommitted
resolves #696: make HaveField great on pointer receivers given only a non-addressable value
Signed-off-by: thediveo <[email protected]>
1 parent f1ff459 commit 4feb9d7

File tree

2 files changed

+11
-6
lines changed

2 files changed

+11
-6
lines changed

matchers/have_field.go

+6-1
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,12 @@ func extractField(actual interface{}, field string, matchername string) (any, er
4040
extractedValue = actualValue.Addr().MethodByName(strings.TrimSuffix(fields[0], "()"))
4141
}
4242
if extractedValue == (reflect.Value{}) {
43-
return nil, missingFieldError(fmt.Sprintf("%s could not find method named '%s' in struct of type %T.", matchername, fields[0], actual))
43+
ptr := reflect.New(actualValue.Type())
44+
ptr.Elem().Set(actualValue)
45+
extractedValue = ptr.MethodByName(strings.TrimSuffix(fields[0], "()"))
46+
if extractedValue == (reflect.Value{}) {
47+
return nil, missingFieldError(fmt.Sprintf("%s could not find method named '%s' in struct of type %T.", matchername, fields[0], actual))
48+
}
4449
}
4550
t := extractedValue.Type()
4651
if t.NumIn() != 0 || t.NumOut() != 1 {

matchers/have_field_test.go

+5-5
Original file line numberDiff line numberDiff line change
@@ -162,23 +162,23 @@ var _ = Describe("HaveField", func() {
162162
})
163163

164164
Describe("receiver lookup", func() {
165-
DescribeTable("(pointer) receiver lookup works",
165+
DescribeTable("(pointer) receiver lookup on book pointer works",
166166
func(field string, expected interface{}) {
167167
Ω(&book).Should(HaveField(field, expected))
168168
},
169169
Entry("non-pointer receiver", "ReceiverTitle()", "Les Miserables"),
170170
Entry("pointer receiver", "PointerReceiverTitle()", "Les Miserables"),
171171
)
172172

173+
It("correctly looks up a pointer receiver on a book value", func() {
174+
Ω(book).Should(HaveField("PointerReceiverTitle()", "Les Miserables"))
175+
})
176+
173177
It("correctly fails", func() {
174178
matcher := HaveField("ReceiverTitle()", "Les Miserables")
175179
answer := struct{}{}
176180
Ω(matcher.Match(answer)).Error().Should(MatchError(
177181
"HaveField could not find method named 'ReceiverTitle()' in struct of type struct {}."))
178-
179-
matcher = HaveField("PointerReceiverTitle()", "Les Miserables")
180-
Ω(matcher.Match(book)).Error().Should(MatchError(
181-
"HaveField could not find method named 'PointerReceiverTitle()' in struct of type matchers_test.Book."))
182182
})
183183
})
184184

0 commit comments

Comments
 (0)