Bee*_*ice 8 unit-testing mocking go testify
考虑 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"})
}
Run Code Online (Sandbox Code Playgroud)
该测试失败,因为当我未超过年龄时testify用于Age: 0比较。我明白了,但我想知道,我该如何断言已通过的部分论点?我希望这个测试能够通过Age,只要Name = John
bla*_*een 12
简而言之,它用mock.argumentMatcher(未导出的)包装任意匹配器函数:
argumentMatcher 执行自定义参数匹配,返回参数是否与期望固定函数匹配。
特别地, 的论证mock.MatchedBy是:
[...] 接受单个参数(预期类型)并返回 bool 的函数
所以你可以按如下方式使用它:
personNameMatcher := mock.MatchedBy(func(p Person) bool {
return p.Name == "John"
})
d.AssertCalled(t, "doWithThing", personNameMatcher)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7790 次 |
| 最近记录: |