当一个函数被多次调用时,有没有办法在每次调用时都调用 AssertCalled
Is there a way to AssertCalled every call when a function is called multiple times
我正在尝试使用 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
并验证 data1
和 data2
确实是用预期的函数调用的。但我只能断言函数的最后一次调用,即 data2
。有什么办法或者我怎样才能用 data1
断言调用?
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
任意次数来记录任意数量的 "called in this and this way" 期望。
我刚刚阅读了源代码,真的。打赌它会比在 SO 上发帖更快。
我正在尝试使用 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
并验证 data1
和 data2
确实是用预期的函数调用的。但我只能断言函数的最后一次调用,即 data2
。有什么办法或者我怎样才能用 data1
断言调用?
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
任意次数来记录任意数量的 "called in this and this way" 期望。
我刚刚阅读了源代码,真的。打赌它会比在 SO 上发帖更快。