GoogleMockでもCppUMockでも、フレームワークはどちらでもいいんですが、ローカル変数として生成されるインスタンスをモックに置き換えられずに困っています。
例えば、以下のような自分で作ったコード(ユニットテスト対象)があったとして、ConcreteCalculatorは他人が作る部位で未完成のため、自分で作っているAddition::add()のユニットテストでは、calc.add関数をモックで置き換えたいのです。
cpp:テスト対象
1#include "target.h" 2#include "concrete_calculator.h" 3 4int Addition::add(const int a, const int b) { 5 ConcreteCalculator calc; 6 return calc.add(a, b); 7}
ユニットテストの実行ファイルをビルド(リンク)する際、ConcreteCalculatorの実態を求められてしまいます。回避するいいアイデアはないでしょうか?
以下、CppUMockを使った場合のサンプルコードです。
text
1ソースコード 2. 3├── include 4│ ├── calculator.h 5│ ├── concrete_calculator.h 減っだだけ先に入手して仮置き 6│ └── target.h 7├── src 8│ └── target.cpp 9└── tests 10 ├── calculator-mock.h 11 └── test_target.cpp
cpp
1calculator.h 2#ifndef CALCULATOR_H 3#define CALCULATOR_H 4 5class Calculator { 6public: 7 virtual int add(const int x, const int y) = 0; 8 virtual ~Calculator() {} 9}; 10 11#endif //CALCULATOR_H
cpp
1concreate_calculator.h 2#ifndef CONCRETE_CALCULATOR_H 3#define CONCRETE_CALCULATOR_H 4 5#include "calculator.h" 6 7class ConcreteCalculator : public Calculator { 8public: 9 int add(const int x, const int y); 10}; 11 12#endif //CONCRETE_CALCULATOR_H
cpp
1target.h 2#ifndef TARGET_H 3#define TARGET_H 4 5#include "calculator.h" 6 7class Addition { 8public: 9 int add(const int a, const int b); 10}; 11 12#endif //TARGET_H
cpp
1target.cpp 2#include "target.h" 3#include "concrete_calculator.h" 4 5int Addition::add(const int a, const int b) { 6 ConcreteCalculator calc; 7 return calc.add(a, b); 8}
cpp
1calculator-mock.h 2#ifndef CALCULATOR_MOCK_H 3#define CALCULATOR_MOCK_H 4 5#include "CppUTestExt/MockSupport.h" 6 7#include "calculator.h" 8 9class CalculatorMock : public Calculator { 10public: 11 ~CalculatorMock() {} 12 int add(const int x, const int y) { 13 14 return mock().actualCall("add").withIntParameter("x", 10).onObject(this).returnIntValue(); // デタラメ 15 } 16}; 17 18#endif //CALCULATOR_MOCK_H
cpp
1test_target.cpp 2#include "CppUTest/CommandLineTestRunner.h" 3#include "CppUTestExt/MockSupport.h" 4#include "target.h" 5#include "calculator-mock.h" 6 7TEST_GROUP(TestFuncGroup) { 8 TEST_SETUP() { 9 10 } 11 12 TEST_TEARDOWN() { 13 mock().clear(); // Mock資源をクリア 14 } 15}; 16 17TEST(TestFuncGroup, Test1) 18{ 19 Calculator *calc = new CalculatorMock(); 20 21 mock().expectOneCall("add").onObject(calc); // デタラメ 22 const int a = 1; 23 const int b = 2; 24 const int expect = a + b; 25 Addition adder; 26 CHECK_EQUAL(expect, adder.add(a, b)); 27 mock().checkExpectations(); 28 29 delete calc; 30} 31 32int main(int argc, char **argv) { 33 // テストランナー 34 return RUN_ALL_TESTS(argc, argv); 35}