如何使用 CppUTest 模拟返回对象的方法

How to mock method returning object using CppUTest

本文关键字:对象 方法 返回 模拟 何使用 CppUTest      更新时间:2023-10-16

我有以下方法:

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

请不要,指针常量指针之间是有区别的。