1

我有以下方法:

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这种形式也行不通。

4

1 回答 1

1

不是按值/引用传递对象,而是按指针传递


例子:

(我在std::map这里使用 -QMap完全一样)

嘲笑

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

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之间存在差异。

于 2016-07-22T19:35:55.493 回答