gmock 多个模拟实例,但只有一个是有效的

gmock Multiple mock instances, but only one is effective

本文关键字:有一个 有效 模拟 实例 gmock      更新时间:2023-10-16

我想测试一个管理某种实体集的类(控制器)。实体是在此类内部创建的,因为工厂在这里会矫枉过正,所以这是我向其中注入模拟的方式:

class TestController : public Controller {
public:
/* Mechanism for a mock injection */
std::shared_ptr<IEntity> create_entity() override {
return temp_entity;
}
/* Variable to hold the entity being injected */
std::shared_ptr<IEntity> temp_entity;
};

生产代码调用控制器类中的create_entity(),我在这里重载了该类,并将结果添加到容器中。temp_entity是我提供模拟的方式,而我提供两个不同模拟实例的测试如下所示:

class MockEntity : public IEntity {
MOCK_METHOD0(perform_operation, bool());
}
TEST(ControllerTest, TestFailure) {
std::shared_ptr<TestController> controller = std::make_shared<TestController>();
std::shared_ptr<MockEntity> entity1 = std::make_shared<MockEntity>();
controller->temp_entity = entity1;
controller->add_entity(); // This invokation fetches the result of create_entity()
std::shared_ptr<MockEntity> entity2 = std::make_shared<MockEntity>();
controller->temp_entity = entity2;
controller->add_entity(); // This invokation fetches the result of create_entity()
EXPECT_CALL(*entity1, perform_operation().WillOnce(::testing::Return(true));
EXPECT_CALL(*entity2, perform_operation().WillOnce(::testing::Return(false));
controller->run();
}

controller.run()只在每个实体上并发执行perform_operation()。

运行测试时,第二个期望中的函数被调用两次,第一个期望中的函数根本不运行。我确信控制器在执行 run()函数之前对实体的两个不同版本进行操作。

我想要做的事情是否存在根本问题?如何在测试中区分我对这两个模拟的期望?我尝试使用在模拟主体中实现的 perform_operation()方法创建两个不同的模拟类,并且在调试器中运行测试时,我仍然两次点击一个模拟类的方法。

测试看起来是正确的,并且如何将模拟注入被测系统的方式是绝对合理的方法。

我想,关键问题出在你正在测试的班级中。我使用以下控制器重建您的测试:

class Controller {
public:
virtual std::shared_ptr<IEntity> create_entity() = 0;
void add_entity() {
auto entity = create_entity();
entities.push_back(entity);
}
void run() {
for(auto e : entities) {
bool i =  e->perform_operation();
}
}
std::vector<std::shared_ptr<IEntity> > entities;
};

对于这个类,测试如预期的那样成功。

相关文章: