当多次调用一个函数时,是否有一种方法可以使AssertCalled每次调用

时间:2020-06-18 10:39:25

标签: unit-testing go testify

我正在尝试使用stretchr/testify进行以下代码的单元测试:

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 */}}))
}

我想调用AssertCalled并验证data1data2的确是由预期函数调用的。但是我只能使用函数的最后一次调用来断言,即使用data2。有什么方法或者如何用data1确认呼叫?

1 个答案:

答案 0 :(得分:1)

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)


}

您似乎可以多次调用.On来记录任意数量的“以此方式调用”的期望值。

真的,我只是阅读了源代码。相信它比在SO上发布要快。