0

我刚开始进行单元测试(使用 BOOST 框架进行测试,但对于模拟我必须使用 Google Mock)并且我遇到了这种情况:

class A
{
  A(){}
  virtual int Method1(int a, int b){return a+b;}
};

class B
{
  static int Method2(int a, int b){ return A().Method1(a,b);}
};

是否可以对 B 类进行测试,以这种方式使用模拟 Method1 而不是真实方法,但不能更改 B 类?我知道这很容易:

class B
{
  B(A *a):a_in_b(a){}
  static int Method2(int a, int b){return a_in_b->Mehod1();}
  A *a_in_b;
};
4

2 回答 2

1

你可以先把你的Class A变成一个单例,就像:

class A
{
    A* Instance();
    virtual int Method1(int a, int b){return a+b;}
    static A* A_instance;
    A(){}
};
A::A_instance = NULL;

然后模拟Class A

#include <gmock/gmock.h>
class MockA : public A
{
    public:
        MOCK_METHOD2(Method1, int(int a, int b));
};

并更改A().A::Instance()->之后;然后,您可以使用以下方法让Class B在运行时调用模拟方法:

MockA mock;
A::A_instance = &mock;
EXPECT_CALL(mock, Method(_, _))
......(you can decide the times and return values of the mock method) 

有关更多信息,您可以在http://code.google.com/p/googlemock/wiki/CookBook阅读 gmock 食谱

于 2012-09-23T15:49:21.610 回答
0

您可以按照http://code.google.com/p/googlemock/wiki/ForDummies上的指南为您构建 A 的模拟:

#include <gmock/gmock.h>
class MockA : public A
{
public:
    MOCK_METHOD2(Method1, int(int a, int b));
};

在 B 类中调用 Method2 之前,确保 B 知道 A 的模拟(用 A 的 Mockobject 分配 B 中的变量)并执行 EXPECT_CALL:

MockA mock;
EXPECT_CALL(mock, Method1(_, _)
    .WillRepeatedly(Return(a + b);

确保变量 a 和 b 在测试的执行上下文中有效。

于 2012-01-21T21:48:46.127 回答