Search code examples
c++unit-testinggoogletestgooglemock

Return mock method argument with gmock


How can I return mock method argument as ON_CALL Return() action argument?

Mock method:

MOCK_METHOD1(foo, int(const std::string&))

Test:

TEST_F(Test, t) {

    //I'm using parametrized tests, this is only for simplicity
    std::map<std::string, int> results = {{"Apple", 1}};

    ON_CALL(obj, foo(_))
        .WillByDefault(
            Return(results.at(argument_from_foo_method)));
}

Solution

  • I find out, use Invoke action:

    ON_CALL(obj, foo(_))
            .WillByDefault(
                Invoke([&](const std::string &s) -> int { return results.at(s); });