如何使用stretchr/testify/mock的AssertCalled方法进行部分匹配断言?

huangapple go评论93阅读模式
英文:

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.MatchedBy

简而言之,它使用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)

huangapple
  • 本文由 发表于 2021年7月12日 23:17:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/68349850.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定