c++trompeloeil

Trompeloeil MAKE_MOCK0 with a template as a return type


When using Trompeloeil to mock unit tests in C++, how can use an unordered_map as a return type?

// This example works fine
// return type is void, my_function takes no arguments 
MAKE_MOCK0(my_function, void(), override);


// This is what I'm trying to do but fails
MAKE_MOCK0(my_function, std::unordered_map<std::string, int>(), override);

Visual Studio is giving the following IntelliSense errors,


Solution

  • Templated return types need to be wrapped in (...). This is explained in: Q. Why can't I mock a function that returns a template?

    // Bad
    MAKE_MOCK0(my_function, std::unordered_map<std::string, int>(), override);
    
    // Good
    MAKE_MOCK0(my_function, (std::unordered_map<std::string, int>()), override);
    

    The C++ preprocessor may have an issue parsing the template with multiple parameters std::string, int. If this occurs, moving the return type to a typedef can help. https://stackoverflow.com/a/38030161/2601293

    typedef std::unordered_map<std::string, int> My_Type;
    ...
    MAKE_MOCK0(my_function, (My_Type()), override);