英文:
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})
// 我不关心传递的Age是多少,只关心Name
d.AssertCalled(t, "doWithThing", Person{Name: "John"})
}
这个测试失败是因为testify
在比较时使用了Age: 0
,而我没有传递年龄。我理解这一点,但我想知道如何对传递的参数的部分进行断言?我希望这个测试通过,无论Age
是多少,只要Name = John
。
英文:
Consider this unit test file in Go. I'm using github.com/stretchr/testify/mock
package.
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"})
}
This tests fails because testify
uses Age: 0
in the comparison when I don't pass an age. I get that, but I'm wondering, how do I assert against a partial of the argument that was passed? I want this test to pass whatever Age
is, so long as Name = John
答案1
得分: 11
简而言之,它使用mock.argumentMatcher
(未导出)将任意匹配器函数包装起来:
> argumentMatcher执行自定义参数匹配,返回参数是否与期望的fixture函数匹配。
特别地,mock.MatchedBy
的参数是:
> [...] 一个接受单个参数(期望类型)并返回布尔值的函数
因此,你可以按照以下方式使用它:
personNameMatcher := mock.MatchedBy(func(p Person) bool {
return p.Name == "John"
})
d.AssertCalled(t, "doWithThing", personNameMatcher)
英文:
Use mock.MatchedBy
.
In short, it wraps an arbitrary matcher function with a mock.argumentMatcher
(unexported):
> argumentMatcher performs custom argument matching, returning whether or not the argument is matched by the expectation fixture function.
In particular, the argument of mock.MatchedBy
is:
> [...] a function accepting a single argument (of the expected type) which returns a bool
So you can use it as follows:
personNameMatcher := mock.MatchedBy(func(p Person) bool {
return p.Name == "John"
})
d.AssertCalled(t, "doWithThing", personNameMatcher)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论