如何使用gmock测试类是否调用了基类的方法 [英] How to use gmock to test that a class calls it's base class' methods
本文介绍了如何使用gmock测试类是否调用了基类的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class Foo {
public:
int x;
int y;
void move(void);
};
class SuperFoo: public Foo {
public:
int age;
void update();
};
SuperFoo::update(void) {
move();
age++;
}
我刚开始使用C ++和单元测试,我有一些类似于上面的代码,并且我想使用gmock来测试SuperFoo::update()
调用基类的move()
方法.应对这种情况的最佳方法是什么?
I'm just starting out with C++ and unit testing, I have some code resembling the above and I want to use gmock to test that SuperFoo::update()
calls the base class' move()
method. What would be that best way to attack this type of situation?
推荐答案
一种方法是使move
方法虚拟化,并创建类的模拟:
One way is to make the move
method virtual, and create a mock of your class:
#include "gtest/gtest.h"
#include "gmock/gmock.h"
class Foo {
public:
int x;
int y;
virtual void move(void);
//^^^^ following works for virtual methods
};
// ...
class TestableSuperFoo : public SuperFoo
{
public:
TestableSuperFoo();
MOCK_METHOD0(move, void ());
void doMove()
{
SuperFoo::move();
}
};
然后在您的测试中,设置相应的通话期望
Then in your test, setup the corresponding call expectations
TEST(SuperFoo, TestUpdate)
{
TestableSuperFoo instance;
// Setup expectations:
// 1) number of times (Times(AtLeast(1)), or Times(1), or ...
// 2) behavior: calling base class "move" (not just mock's) if "move"
// has side-effects required by "update"
EXPECT_CALL(instance, move()).Times(testing::AtLeast(1))
.WillRepeatedly(testing::InvokeWithoutArgs(&instance, &TestableSuperFoo::doMove));
const int someValue = 42;
instance.age = someValue;
// Act
instance.update();
// Assert
EXPECT_EQ(someValue+1, instance.age);
}
这篇关于如何使用gmock测试类是否调用了基类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文