将 std::string 和 StrictMock<MockClass> 的映射注入到被测试的类中

问题描述 投票:0回答:1

我有一个类将按钮路由到各个工作人员。我的工作人员正在接受测试,我现在需要测试我的路由器。问题是我的路由器无法像我最初期望的那样接受模拟地图。很多代码被删除,但我相信下面的代码应该足以产生相同的结果。

路由器构造函数签名如下:

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

我创建了一个模拟,如下所示:

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

我尝试为路由器创建模拟地图,如下所示:

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

运行测试时,我发现

ButtonRouter
的构造函数没有匹配的函数调用要在 MOCK_WorkerInterfaces 映射中传递。像这样传递模拟有问题吗?我应该直接将它们注入构造函数而不是映射到构造函数吗?

c++ googletest googlemock
1个回答
0
投票

这个错误的声明

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

应该是

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));
© www.soinside.com 2019 - 2024. All rights reserved.