unit-testing - 如何断言与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 执行自定义参数匹配,返回参数是否与期望夹具函数匹配。
特别是, 的论点mock.MatchedBy
是:
[...] 一个接受单个参数(预期类型)的函数,它返回一个布尔值
因此,您可以按如下方式使用它:
personNameMatcher := mock.MatchedBy(func(p Person) bool {
return p.Name == "John"
})
d.AssertCalled(t, "doWithThing", personNameMatcher)
推荐阅读
- javascript - 能够在 Ajax 成功时再次使用 ajax
- javascript - firebase.auth(...).getUserByEmail 不是函数
- python - 何时用 Celery Groups 扇出与延迟
- time - 服务块中的 Anylogic 测量时间
- c# - 如何使用 ajax 传递 from.serialize() 和数组值?
- javascript - 如何使用 VUE 2 Composition API 正确设置 npm 包?
- django - 保存 submit.created_utc 值并保存在 django models.DateTimeField
- elasticsearch - 查询以在弹性搜索中提升和排序数据
- node.js - 如何检查 url 路径/路径名是否存在(Node.js URL)
- java - 设置回原始语言环境不起作用