首页 > 解决方案 > 如何断言与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

标签: unit-testinggomockingtestify

解决方案


使用mock.MatchedBy.

简而言之,它用mock.argumentMatcher(未导出的)包装了一个任意匹配器函数:

argumentMatcher 执行自定义参数匹配,返回参数是否与期望夹具函数匹配。

特别是, 的论点mock.MatchedBy是:

[...] 一个接受单个参数(预期类型)的函数,它返回一个布尔值

因此,您可以按如下方式使用它:

personNameMatcher := mock.MatchedBy(func(p Person) bool {
    return p.Name == "John"
})
d.AssertCalled(t, "doWithThing", personNameMatcher)

推荐阅读