unit-testing - 有没有办法在多次调用函数时每次调用 AssertCalled
问题描述
我正在尝试使用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
解决方案
文档中的示例:
/*
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 上发帖更快。
推荐阅读
- r - 使用 group_by 和 dplyr 根据前一个条件计算一个事件的概率
- xml - 如何使用 curl 获取 jenkins config.xml(jenkins 根配置)文件?
- asp.net-core - 使用 ajax 调用 JavaScript 库时,它没有继承到 modal
- scala - spark-submit scala - 具有依赖项的 zip 文件
- android - 2关于CameraX闪烁的问题
- abp - 为 abp-dynamic-form 中的下拉列表扩展实体和配置外键的推荐方法
- android - 如何在android studio中找到未在xml中设置的字符串?
- javascript - Vue 计算属性不会在更新其反应性依赖项时更新
- java - 配置 Spring Boot 日志记录的最佳方法在哪里?在 application.properties 或 xml 文件 (logback-spring.xml) 中?
- javascript - 从javascript中的类方法返回一个值