1

I've following method:

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;
}

an I try to write mock which can return QMap prepared in test:

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

but I don't know how to mock the return value? I would like to use the mock in following way in TEST function:

QMap<QString, int> fake_map;
fake_map.insert("ABC", 1);
mock().expectOneCall("getConfig").andReturnValue(fake_map);

I cannot find such example in CppUTest Mocking documentation. I also know that .andReturnValue in this form will also not work.

1 Answer 1

1

Instead of passing the object by-value / -reference, pass by-pointer.


Example:

(I'm using an std::map here – QMap is exactly the same)

Mock

You get the return value for the mock by the return#####Value() methods. Since returnPointerValue() returns a void* you have to cast it to proper pointer type. Then you can return by-value by dereferencing that pointer.

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

Test

The expected return value is passed by pointer:

TEST(MapMockTest, mockReturningAMap)
{
    std::map<std::string, int> expected = { {"abc", 123} };
    mock().expectOneCall("getConfig").andReturnValue(&expected);

    auto cfg = getConfig();
    CHECK_EQUAL(123, cfg["abc"]);
}

Please not, there's a difference between Pointer and ConstPointer.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.