I am trying to unit test with stretchr/testify for code like the following:
func (c *MyClient) upsertData(data MyObject) {
upsertToDatabase(data)
}
func doSomething(c *MyClient) {
data1, data2 := getSomeData()
c.upsertToDatabase(data1)
c.upsertToDatabase(data2)
}
// Unit test.
func TestDoSomething(t *testing.T) {
c := mock.MyClient{}
doSomething(c)
/* The following line checking for data1 upsert failed.
* require.True(t, c.AssertCalled(t, "upsertToDatabase", mock.MatchedBy(func(data MyObject) bool { return data == MyObject{expectedObject1 /* data2 */}})) */
require.True(t, c.AssertCalled(t, "upsertToDatabase", mock.MatchedBy(func(data MyObject) bool { return data == MyObject{expectedObject1 /* data2 */}}))
}
I want to call AssertCalled
and verify that both data1
and data2
are indeed called with the expected function. But I can only assert with the last call of the function, i.e. with data2
. Is there any way or how can I assert the call with data1
as well?
The example in the docs:
/*
Actual test functions
*/
// TestSomething is an example of how to use our test object to
// make assertions about some target code we are testing.
func TestSomething(t *testing.T) {
// create an instance of our test object
testObj := new(MyMockedObject)
// setup expectations
testObj.On("DoSomething", 123).Return(true, nil)
// call the code we are testing
targetFuncThatDoesSomethingWithObj(testObj)
// assert that the expectations were met
testObj.AssertExpectations(t)
}
looks like you can call .On
any number of times to record any number of "called in this and this way" expectations.
I'd just read the source code, really. Bet it'd be faster than posting on SO.