[英]How to simulate an EXPECT_CALL with gtest
In the code below I tried to explain my problem on a basic model.在下面的代码中,我试图在基本模型上解释我的问题。
class A
{
public:
A() {}
virtual void foo() {}
virtual ~A(){}
//...
};
class B : public A{
public:
B(){}
//...
//does not contain the override function foo()
};
class MustBeTested{
public:
MustBeTested(){
//...
}
void function()
{
m_elem->foo();
//...
}
private:
B* m_elem;
};
class Mock : public B {
public:
Mock() {}
MOCK0(foo, void());
};
//test function from above class
void TestFunction
{
Mock* dummy = new Mock;
EXPECT_CALL(*dummy, foo()).Times(1);
//i know it is wrong becase the called method is A::foo();
}
I have a basic class A that contains a virtual method.我有一个包含虚方法的基本类 A。 Derivative class B no longer contains the overwritten method foo ().
派生类 B 不再包含被覆盖的方法 foo()。 The MustBeTested class contains the function to be tested, the class member is type B *.
MustBeTested 类包含要测试的函数,类成员类型为 B *。 Initially without looking I started to make a Mock class derived from B to simulate EXPECT_CALL ().
最初没有看我开始制作一个从 B 派生的 Mock 类来模拟 EXPECT_CALL()。 I realized that it is not possible because the method in A :: foo () will always be called.
我意识到这是不可能的,因为 A::foo() 中的方法将始终被调用。
My question is, if there is a workaround without making changes to the class A or B code?我的问题是,是否有一种不更改 A 类或 B 类代码的解决方法?
foo
in B
is not overriden, but it is there - with the default implementation from A
. B
foo
没有被覆盖,但它在那里 - 具有来自A
的默认实现。 foo
is virtual and can be overriden in classes that derive from B
, like your Mock
(that wouldn't be possible if foo
was marked final
in B
). foo
是虚拟的,可以在从B
派生的类中被覆盖,就像你的Mock
(如果foo
在B
被标记为final
,那是不可能的)。 Your code will work if you will use dependency injection in MustBeTested
, see Dependency injection with unique_ptr to mock .如果您将在
MustBeTested
使用依赖注入,您的代码将起作用,请参阅使用 unique_ptr 模拟的依赖注入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.