Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang Mocking a call with some parameters in body with values not fixed

Tags:

go

go-testing

I am mocking a method call as follows:

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

which works fine.

Now, here, instead of passing a fixed value for the field creationDate, if I want to generalize it so it will work for any value passed, how can I achieve that? I am pretty new to Go, so not sure how to do this

the values for creationDate could be any value like - 2021-03-19T18:57:16.589Z or 2022-04-23T14:17:56.589Z etc. I just dont want to limit the mock call to work for a fixed value of creationDate, but I would like it to work for any date string passed

like image 378
user1892775 Avatar asked Oct 18 '25 11:10

user1892775


1 Answers

Assuming you're using github.com/stretchr/testify/mock, you should be able to use mock.MatchedBy() to match on specific parts of the argument. For example:

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

However, I find this to be most useful when needing to take a different action depending on the input. If you're simply verifying addProd was called with a specific argument, consider asserting that instead:

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)
like image 161
Gavin Avatar answered Oct 20 '25 04:10

Gavin