-2

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?

3tbraden
  • 667
  • 1
  • 10
  • 21

1 Answers1

2

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.

kostix
  • 51,517
  • 14
  • 93
  • 176
  • I am using `.On` to mock `c.upsertToDatabase()` but the function that I am testing is `doSomething(c)` where multiple instances of `c.upsertToDatabase()` are called. Even if I set up different return cases in `c.On("upsertToDatabase)`, there will be no way to verify `c.upsertToDatabase()` are actually called multiple times in `doSomething()`? – 3tbraden Jun 19 '20 at 01:49
  • 1
    Ah I think I got it now. So I have to do `c.On("upsertToDatabase", data1).Return()` and `c.On("upsertToDatabase", data2).Return()`, any missing call on `c.upsertToDatabase(data1)` or `c.upsertToDatabase(data2)` will fail `c.AssertExpectations(t)`. – 3tbraden Jun 19 '20 at 02:16