How to use gmock to test that a class calls it's base class' methods

◇◆丶佛笑我妖孽 提交于 2019-12-22 05:22:04

问题


class Foo {
public:
    int x;
    int y;

    void move(void);
};

class SuperFoo: public Foo {
public:
    int age;

    void update();
};

SuperFoo::update(void) {
    move();
    age++;
}

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?


回答1:


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);
}


来源:https://stackoverflow.com/questions/25487301/how-to-use-gmock-to-test-that-a-class-calls-its-base-class-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!