c++ - 如何使用 CppUTest 模拟方法返回对象

标签 c++ unit-testing 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 Mocking 文档中找不到这样的例子。我也知道这种形式的 .andReturnValue 也不起作用。

最佳答案

不是通过值/引用传递对象,通过指针传递


示例:

(我在这里使用的是 std::mapQMap 完全一样)

模拟

您可以通过 return#####Value() 方法获取模拟的返回值。由于 returnPointerValue() 返回一个 void*,您必须将其转换为正确的指针类型。然后您可以通过取消引用该指针按值返回。

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"]);
}

请注意,PointerConstPointer 是有区别的。

关于c++ - 如何使用 CppUTest 模拟方法返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38323676/

相关文章:

C++ 默认参数 : is it possible to override a default parameter without overriding earlier default parameters

c++ - 在现实生活中管理 char *

c++ - DecideBufferSize 值似乎被忽略

unit-testing - 如何在 VueJS 中测试计算属性?

c# - 为什么在设置对 "System.IO.FileNotFoundException: Could not load file or assembly"的引用时得到 "copylocal=false"?

unit-testing - 为什么 chefspec 找不到 chef_handler Recipe ?

c++ - 使用 Assembly 和 C++ 调用一个函数两次

c++ - 使用CppUTest问题 “expected type-specifier before ‘(’ token 进行Yaml-cpp配置解析器测试”

c - 为什么链接存档时会出现 'multiple definition' 错误?

c++ - CppUTest 单元测试框架多重定义异常