出于教育目的,我正在用Qt和C ++编写类似Pacman的游戏。游戏的主要部分正常运行,但是现在我需要使用Googletest框架对其进行测试。我阅读了有关依赖注入的信息,并尝试将其实现到我的项目中。
项目由几个类组成,如ghost,pacman等,以及一个“ Game”类,它是QGraphicsView,还包含指向这些对象的指针。问题是,当我构造“游戏”类并将poiter传递给mock_pacman对象时,它不使用它的模拟方法,并且似乎也无法检测到对mock_pacman的使用(当我尝试EXPECT_CALL(..)时,测试失败了) 。作为示例,我将只发布涉及最简单方法的部分代码:
“游戏”类的构造函数:
Game(QWidget * parent=nullptr) {...};
Game(QVector<ghost*> GhostArray, pacman * _player, PacmanBoard * Board, QWidget * parent=nullptr)
Secound构造函数只是将_player当作成员
我要测试的方法:
int Game::getPacmanDirection()
{
return player->getActualDirection();
}
吃豆子的模拟:
class mock_pacman: public pacman
{
public:
virtual ~mock_pacman()=default;
MOCK_METHOD1(keyPressEvent,void(QKeyEvent *));
MOCK_METHOD0(getPosition,QPointF());
MOCK_METHOD1(setPosition,void(QPointF()));
MOCK_METHOD0(update,void());
MOCK_METHOD0(getAnimationPhase,void());
MOCK_METHOD1(setAnimationPhase,void(int));
MOCK_METHOD0(animate,void());
MOCK_METHOD0(getActualDirection,int());
MOCK_METHOD0(getLastMove,QPoint());
MOCK_CONST_METHOD0(pos,QPointF());
};
Google测试:
TEST(GameClassTests, GettingPacmanRealDirection)
{
mock_pacman * m_pacman = new mock_pacman();
mock_pacmanboard m_board;
mock_ghost ghost0(0);
mock_ghost ghost1(1);
mock_ghost ghost2(2);
mock_ghost ghost3(3);
QVector<ghost*> m_ghost_vector{&ghost0,&ghost1,&ghost2,&ghost3};
EXPECT_CALL(*m_pacman,getActualDirection());
Game * game = new Game(m_ghost_vector,m_pacman,&m_board);
game->getPacmanDirection();
delete m_pacman;
};
测试重试:
[ RUN ] GameClassTests.GettingPacmanRealDirection
../PacmanTests/tst_alltests.h:110: Failure
Actual function call count doesn't match EXPECT_CALL(*m_pacman, getActualDirection())...
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] GameClassTests.GettingPacmanRealDirection (4 ms)
pacman原始类中的函数getActualDirection()被标记为虚拟。 我试图用其他方法来做到这一点,使用测试夹具,通过参考和许多其他变体。
我在哪里弄错了?