1

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

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

效果很好。

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

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

4

1 回答 1

1

假设您正在使用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)
于 2021-03-19T20:04:48.883 回答