gmock 多个模拟实例,但只有一个是有效的
gmock Multiple mock instances, but only one is effective
我想测试一个管理某种实体集的类(控制器)。实体是在此类内部创建的,因为工厂在这里会矫枉过正,所以这是我向其中注入模拟的方式:
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;
};
对于这个类,测试如预期的那样成功。
相关文章:
- 有一个打印语句的函数是一种糟糕的编程实践吗
- VSCode-有一个红色下划线,但程序构建和运行正确,并且出现配音错误
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 有没有可能有一个只有ADL才能找到的非好友功能
- 有哪些有效的方法可以消除一组 100 万个字符串>重复数据?
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 我的程序有一个保存配置文件的GUI,如何双击此配置文件以直接加载带有配置数据的GUI?
- 在学习数据结构之前对STL有一个了解是好的吗?
- 我在 .h 中有一个枚举类,并且在.cpp错误中有一个运算符重载:与"运算符<<不匹配
- 如何在 Gnuplot 中分别绘制 2 个文件数据?我有一个文件"sin.txt",另一个文件"cos.txt",我想将它们分别绘制在一个图表上
- 是否可以在C++中有一个"generic"模板参数,该参数可以是非类型模板参数或类型?
- 我的输出中有一个额外的 0,为什么会这样
- 如何确保迷宫总是有一个有效的路径C++
- 如何验证字符串是有效的双精度(即使它有一个点)
- C++ 为什么这些构造函数调用中有 3 个有效,但有一个不起作用?
- 指针和类有问题。两个相同的类,其中一个有效,一个无效
- 以下代码有什么区别,为什么一个有效而另一个无效?
- 一个有效的指向成员的指针能和一个NULL指针有相同的值吗?
- 是否有一个Windows c++ API来验证Windows用户名/域名是本地机器上的有效帐户(没有密码)
- 设计模式-是否有一个有效的案例可以创建一个立即被销毁且不直接在C++中使用的临时模式