7
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()方法。攻击这种情况的最佳方法是什么?

4

1 回答 1

4

一种方法是使move方法虚拟化,并为您的类创建一个模拟:

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

然后在您的测试中,设置相应的呼叫期望

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);
}
于 2014-08-25T15:01:35.223 回答