gpt4 book ai didi

Golang 在正文中使用某些参数模拟调用,但值不固定

转载 作者:行者123 更新时间:2023-12-05 01:30:51 24 4
gpt4 key购买 nike

我正在模拟一个方法调用,如下所示:

tctx.someMock.On("addProd",
product.NewAddProductParamsWithContext(ctx).
WithID("someid").
WithCreateRequest(pro.CreateProdBody{
creationDate: "someDate" ,
}), nil).
Return(nil, nil)

效果很好。

现在,在这里,不是为字段 creationDate 传递一个固定值,如果我想概括它以便它适用于任何传递的值,我该如何实现呢?我是 Go 的新手,所以不知道该怎么做

creationDate 的值可以是任何值,例如 - 2021-03-19T18:57:16.589Z2022-04-23T14:17:56.589Z 等。我只是不想将模拟调用限制为对 creationDate 的固定值起作用,但我希望它对传递的任何日期字符串起作用

最佳答案

假设您正在使用 github.com/stretchr/testify/mock,您应该能够使用 mock.MatchedBy() 来匹配争论。例如:

tctx.someMock.On("addProd", mock.MatchedBy(func(i interface{}) bool {
p := i.(*product.AddProductParams)
return p.ID() == "someid"
})).Return(nil, nil)

但是,我发现这在需要根据输入采取不同的操作时最有用。如果您只是验证使用特定参数调用了 addProd,请考虑断言:

tctx.someMock.On("addProd", mock.Anything).Return(nil, nil)

...

tctx.someMock.AssertCalled(t, "addProd", mock.MatchedBy(func(i interface{}) bool {
p := i.(*product.AddProductParams)
return p.ID() == "someid"
})).Return(nil, nil)

关于Golang 在正文中使用某些参数模拟调用,但值不固定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66714506/

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