C ++ GoogleMock模拟方法调用同一个类的另一个方法

时间:2018-02-08 23:06:44

标签: c++ unit-testing

我在这里看到这个问题: Can googlemock mock method calls from within other method calls of the same class?

并尝试实施答案,但它对我不起作用。

我修改了链接问题实现以删除模拟ReturnInputPlus1(),这是接受的答案所暗示的:

using ::testing::Invoke;
using ::testing::_;
using ::testing::Return;

class MyClass
{
  public:
    MyClass() : x(1) {}
    virtual ~MyClass() {}

    int ReturnInput(int x) { return x; }
    int ReturnInputPlus1(int x) { return ReturnInput(x) + 1; }
  private:
    int x;
};

class MockMyClass : public MyClass
{
public:
    MockMyClass()
    {
        ON_CALL(*this, ReturnInput(_)).WillByDefault(Invoke(&real, &MyClass::ReturnInput));
    }
    virtual ~MockMyClass() {}

    MOCK_METHOD1(ReturnInput, int(int y));

private:
    MyClass real;
};

TEST(MyClassTest, mockUseClassMethod)
{
    MockMyClass mock;

    EXPECT_CALL(mock, ReturnInput(_))
        .WillOnce(Return(2));

    EXPECT_EQ(3, mock.ReturnInputPlus1(1));
}

这仍然会返回相同的失败

/projects/tests/cpp/google-test/test.cpp:46: Failure
      Expected: 3
To be equal to: mock.ReturnInputPlus1(1)
      Which is: 2
/projects/tests/cpp/google-test/test.cpp:41: Failure
Actual function call count doesn't match EXPECT_CALL(mock, ReturnInput(_))...
         Expected: to be called once
           Actual: never called - unsatisfied and active

1 个答案:

答案 0 :(得分:0)

如果没有在MyClass virtual中创建方法,我看不到一种将内部调用重定向到模拟行为的方法。

下面是一个有效的示例:

  • 删除了real成员,该模拟仍在继承MyClass
  • 我猜想“诀窍”是要知道可以调用这样的父类行为:mock.MyClass::ReturnInputPlus1(1)qualified name lookup)并了解dynamic dispatch会导致MockMyClass的使用: :ReturnInput。
  • 我不太确定MyClass :: x想要实现什么,因为它会被函数参数遮盖。

class MyClass
{
public:
    MyClass()
        : m_x(1)
    {
    }
    virtual ~MyClass() {}

    virtual int ReturnInput(int x) { return x; }
    virtual int ReturnInputPlus1(int x) { return ReturnInput(x) + 1; }

private:
    int m_x;
};

class MockMyClass : public MyClass
{
public:
    MockMyClass()
        : MyClass()
    {
        ON_CALL(*this, ReturnInput(_)).WillByDefault(Invoke(this, &MyClass::ReturnInput));
    }
    virtual ~MockMyClass() {}

    MOCK_METHOD1(ReturnInput, int(int y));
    MOCK_METHOD1(ReturnInputPlus1, int(int y));
};

TEST(MyClassTest, mockUseClassMethod)
{
    MockMyClass mock;

    EXPECT_CALL(mock, ReturnInput(_)).WillOnce(Return(2));

    EXPECT_EQ(3, mock.MyClass::ReturnInputPlus1(1));
}