c++googletestgooglemock

Injecting a map of std::string and StrictMock<MockClass> into a class under test


I have a class that routes buttons to respective workers. My workers are under test and I now need to get my router under test. The problem is that my router is unable to take in the map of mocks like I would initially expect it to. A lot of the code is stripped out but I believe the following code should be enough to produce the same result.

The router constructor signature is as follows:

ButtonRouter::ButtonRouter(std::map<std::string, WorkerInterface*> in_map)

I created a mock as follows:

class MOCK_WorkerInterface : public WorkerInterface
{
    MOCK_METHOD(void, doSomething, (), (override));
}

I tried creating a map of mocks for the router as follows:

std::map<std::string, StrictMock<MOCK_WorkerInterface>*> my_map;

StrictMock<MOCK_WorkerInterface>* worker_1 = new StrictMock<MOCK_WorkerInterface>();
StrictMock<MOCK_WorkerInterface>* worker_2 = new StrictMock<MOCK_WorkerInterface>();
StrictMock<MOCK_WorkerInterface>* worker_3 = new StrictMock<MOCK_WorkerInterface>();
...

my_map.insert(std::make_pair("worker_1", worker_1));
my_map.insert(std::make_pair("worker_2", worker_2));
my_map.insert(std::make_pair("worker_3", worker_3));
...

ButtonRouter* button_router = new ButtonRouter(my_map);

When running the test I get that there is no matching function call for the ButtonRouter's constructor to be passed in a map of MOCK_WorkerInterfaces. Is there an issue with passing in mocks like this? Should I just directly inject them into the constructor rather than to a map then to the constructor?


Solution

  • This wrong declaration

    std::map<std::string, StrictMock<MOCK_WorkerInterface>*> my_map;
    

    should be

    std::map<std::string, WorkerInterface*> my_map;
    
    auto* worker_1 = new StrictMock<MOCK_WorkerInterface>();
    auto* worker_2 = new StrictMock<MOCK_WorkerInterface>();
    auto* worker_3 = new StrictMock<MOCK_WorkerInterface>();
    
    my_map.insert(std::make_pair("worker_1", worker_1));
    my_map.insert(std::make_pair("worker_2", worker_2));
    my_map.insert(std::make_pair("worker_3", worker_3));