如何使用 CppUTest 模拟返回对象的方法
How to mock method returning object using CppUTest
我有以下方法:
QMap<QString, int> DefaultConfig::getConfig()
{
QMap<QString, int> result;
result.insert("Error", LOG_LOCAL0);
result.insert("Application", LOG_LOCAL1);
result.insert("System", LOG_LOCAL2);
result.insert("Debug", LOG_LOCAL3);
result.insert("Trace", LOG_LOCAL4);
return result;
}
我尝试编写可以返回测试中准备的QMap的模拟:
QMap<QString, int> DefaultConfig::getConfig() {
mock().actualCall("getConfig");
return ?
}
但我不知道如何模拟返回值?我想在函数中通过以下方式使用模拟TEST
:
QMap<QString, int> fake_map;
fake_map.insert("ABC", 1);
mock().expectOneCall("getConfig").andReturnValue(fake_map);
我在 CppUTest 模拟文档中找不到这样的例子。我也知道这种形式的.andReturnValue
也行不通。
与其传递对象 by-value/-reference,不如传递 by-pointer。
例:
(我在这里使用std::map
- QMap
完全相同)
模拟
您可以通过return#####Value()
方法获取模拟的返回值。由于returnPointerValue()
返回一个void*
因此您必须将其转换为正确的指针类型。然后,您可以通过取消引用该指针来返回 by-value。
std::map<std::string, int> getConfig()
{
auto returnValue = mock().actualCall("getConfig")
.returnPointerValue();
return *static_cast<std::map<std::string, int>*>(returnValue);
}
测试
预期返回值通过指针传递:
TEST(MapMockTest, mockReturningAMap)
{
std::map<std::string, int> expected = { {"abc", 123} };
mock().expectOneCall("getConfig").andReturnValue(&expected);
auto cfg = getConfig();
CHECK_EQUAL(123, cfg["abc"]);
}
请不要,指针和常量指针之间是有区别的。
相关文章:
- 使用std::函数映射对象方法
- 正在调用shared_ptr对象方法
- 检查哪个对象调用了另一个对象的对象方法
- 如何在C++中循环访问未知对象方法?
- c++ 替换调用对象方法的宏函数
- 我能否通过将函数实现为类对象方法来避免使用互斥锁
- 我可以制作一个对象方法,如果单独调用,它将自行修改,但如果在复制初始化期间调用,则会返回一个新对象?
- 如何让两个不同的对象方法相互用作参数
- 在创建 c++ 期间调用对象方法
- 扩展中的日期时间对象方法C++问题
- 将对象方法从向量应用于C 的第二个向量中的对象
- 将 C++/CLI 对象指针传递给本机对象方法
- 多态性的面向对象方法
- 将对象方法传递到变量
- C :使用Main中定义的对象方法的函数
- 有关使用矢量迭代器访问对象方法的问题
- 定义可以执行对象方法和独立函数的函数时出现问题
- 调用列表中子对象方法的最佳方法
- main.cpp:(.text+0x8f):对[对象方法]的未定义引用
- cpp 从需要超类对象的函数访问子类对象方法