如何断言与 stretchr/testify/mock AssertCalled 的部分匹配?
How to assert a partial match with stretchr/testify/mock AssertCalled?
在 Go 中考虑这个单元测试文件。我正在使用 github.com/stretchr/testify/mock
包。
type Person struct {Name string; Age int}
type Doer struct { mock.Mock }
func (d *Doer) doWithThing(arg Person) {
fmt.Printf("doWithThing %v\n", arg)
d.Called(arg)
}
func TestDoer(t *testing.T) {
d := new(Doer)
d.On("doWithThing", mock.Anything).Return()
d.doWithThing(Person{Name: "John", Age: 7})
// I don't care what Age was passed. Only Name
d.AssertCalled(t, "doWithThing", Person{Name: "John"})
}
此测试失败,因为 testify
在我未过年龄时在比较中使用 Age: 0
。我明白了,但我想知道,我如何断言通过的部分论点?我希望这个测试通过 Age
是什么,只要 Name = John
简而言之,它用 mock.argumentMatcher
(未导出)包装任意匹配器函数:
argumentMatcher performs custom argument matching, returning whether or not the argument is matched by the expectation fixture function.
特别是mock.MatchedBy
的参数是:
[...] a function accepting a single argument (of the expected type) which returns a bool
所以你可以这样使用它:
personNameMatcher := mock.MatchedBy(func(p Person) bool {
return p.Name == "John"
})
d.AssertCalled(t, "doWithThing", personNameMatcher)
在 Go 中考虑这个单元测试文件。我正在使用 github.com/stretchr/testify/mock
包。
type Person struct {Name string; Age int}
type Doer struct { mock.Mock }
func (d *Doer) doWithThing(arg Person) {
fmt.Printf("doWithThing %v\n", arg)
d.Called(arg)
}
func TestDoer(t *testing.T) {
d := new(Doer)
d.On("doWithThing", mock.Anything).Return()
d.doWithThing(Person{Name: "John", Age: 7})
// I don't care what Age was passed. Only Name
d.AssertCalled(t, "doWithThing", Person{Name: "John"})
}
此测试失败,因为 testify
在我未过年龄时在比较中使用 Age: 0
。我明白了,但我想知道,我如何断言通过的部分论点?我希望这个测试通过 Age
是什么,只要 Name = John
简而言之,它用 mock.argumentMatcher
(未导出)包装任意匹配器函数:
argumentMatcher performs custom argument matching, returning whether or not the argument is matched by the expectation fixture function.
特别是mock.MatchedBy
的参数是:
[...] a function accepting a single argument (of the expected type) which returns a bool
所以你可以这样使用它:
personNameMatcher := mock.MatchedBy(func(p Person) bool {
return p.Name == "John"
})
d.AssertCalled(t, "doWithThing", personNameMatcher)