gpt4 book ai didi

unit-testing - 如何断言与 stretr/testify/mock AssertCalled 的部分匹配?

转载 作者:行者123 更新时间:2023-12-05 01:58:45 25 4
gpt4 key购买 nike

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

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

argumentMatcher performs custom argument matching, returning whether or not the argument is matched by the expectation fixture function.

特别是,mock.MatchedBy 的参数是:

[...] a function accepting a single argument (of the expected type) which returns a bool

所以你可以像下面这样使用它:

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

关于unit-testing - 如何断言与 stretr/testify/mock AssertCalled 的部分匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68349850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com