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のテストを行うことは可能ですか?そのようにして、実際のメソッドの代わりにモックされたメソッド1を使用しますが、クラス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

You could follow the guide on http://code.google.com/p/googlemock/wiki/ForDummies to build you a mock of A:

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

Before calling Method2 in class B make sure B knows the mock of A (assign the variable in B with the Mockobject of A) and execute an EXPECT_CALL:

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

Make sure that the variables a and b are valid in the execution context of the test.

于 2012-01-21T21:48:46.127 に答える