如何使用 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;
}

我尝试编写模拟,它可以 return QMap 在测试中准备:

QMap<QString, int> DefaultConfig::getConfig() {
    mock().actualCall("getConfig");
    return ?
}

但我不知道如何模拟 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() 方法获得模拟的 return 值。由于 returnPointerValue() return 是一个 void*,因此您必须将其转换为正确的指针类型。然后,您可以通过取消引用该指针来 return 按值。

std::map<std::string, int> getConfig()
{
    auto returnValue = mock().actualCall("getConfig")
                                .returnPointerValue();
    return *static_cast<std::map<std::string, int>*>(returnValue);
}

测试

预期的return值由指针传递:

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 是有区别的。