【发布时间】:2019-11-19 18:30:22
【问题描述】:
我的测试中有一个测试夹具,因此我不必重复实例化我的类的对象,但我不确定如何使用模拟。简单来说,类是这样定义的:
class Class1 {
public:
Class1(std::shared_ptr<Class2> class_two);
void doThisThing() { doThatThing(); }
}
class Class2 {
public:
Class2(Class3* class3_ptr);
int doThatThing();
}
(类 1 使用指向类 2 的共享指针构造。类 2 使用指向类 3 的指针构造。类 1 调用函数“doThisThing”,该函数调用类 2 的函数 doThatThing。)
我需要为 doThatThing()(以及 Class2 的其余函数)创建一个模拟,但无法弄清楚如何将模拟对象传递给 Class 1。这是我目前在测试代码中的内容:
class TestClass1 : public ::testing::Test {
TestClass1(){
//Construct instance of Class1 and store as member variable
std::shared_ptr<Class3> class_three = std::make_shared<Class3>();
std::shared_ptr<Class2> class_two = std::make_shared<Class2>((Class3*)class_three.get());
class_one = new Class1(class_two);
};
Class1* class_one;
}
MockClass2 : public Class2 {
MOCK_METHOD0(doThatThing, int());
}
TEST_F(TestClass1, doThatThingTest){
MockClass2 mockObj;
**THIS IS WHERE I'M STUCK. How do I get that mockObj into my TestClass1 Fixture? As of now, it is calling the actual function, not the mock***
class_one->doThatThing();
EXPECT_CALL(mockObj, doThatThing());
}
我必须对实际代码进行抽象和简化,所以我希望以上内容有意义。
【问题讨论】:
-
Google mock 没有魔法(唉!),当它最初不是这样的时候,它不能做多态的东西。您需要在原始代码中使用虚拟函数或模板才能模拟它。
标签: c++ googletest googlemock