Hippomocks と C++ は初めてです。例外がキャッチされる Unittest を作成しようとしています。このために、次のテストを作成しました。
#include <ostream>
#include "../Mocks/hippomocks.h"
/////// Mocking Test Classes /////////////////////
class IBar { // class used inside test class
public:
virtual ~IBar() {}
virtual int c(std::string s, int i) // function to be mocked
{
if ( s == std::string("Hallole" ))
{
return 5;
}
else
{
return 7;
}
};
};
class Foo1 {
public:
Foo1(){ std::cout << "hier1" << std::endl;};
IBar *bar;
int a() // function to under (unit-)test
{
return this->bar->c("Hallole", 3);
};
};
class Foo2 {
public:
Foo2(){ std::cout << "hier2" << std::endl;};
IBar bar;
int a() // function to under (unit-)test
{
return this->bar.c("Hallole", 3);
};
};
/////// Mocking Test Classes End /////////////////////
void test(){
/////// Test hippomock /////////////////////
MockRepository mocks;
IBar *b = mocks.Mock<IBar>();
Foo1 *g = new Foo1();
g->bar = b;
mocks.ExpectCall(g->bar, IBar::c).Throw(std::exception());
CPPUNIT_ASSERT_THROW (g->a(), std::exception);
/////// Test hippomock end /////////////////////
}
void TestTest::test_a(){
/////// Test hippomock /////////////////////
MockRepository mocks;
IBar *b = mocks.Mock<IBar>();
Foo2 *g = new Foo2();
// g->bar = *b;
memcpy(&g->bar, b, sizeof(*b));
mocks.ExpectCall(b, IBar::c).Throw(std::exception());
CPPUNIT_ASSERT_THROW (g->a(), std::exception);
/////// Test hippomock end /////////////////////
}
test()
正しく動作します。これはhttps://app.assembla.com/wiki/show/hippomocks/Tutorial_3_0で見つけた例です。
しかし、実行してtest_a()
も例外はスローされず、次のようになります。
uncaught exception of type HippoMocks::CallMissingException
- Function with expectation not called!
Expections set:
TestTest.cpp(97) Expectation for IBar::c(...) on the mock at 0x0x7f14dc006d50 was not satisfied.
Foo1 と Foo2 の違いは、Foo1 では属性 bar がポインターであり、Foo2 では値であることです。私の質問は次のとおりです。
- 異なる動作があるのはなぜですか?
memcpy(&g->bar, b, sizeof(*b))
というか、モック オブジェクト bを設定したのに、なぜ例外がスローされない のでしょうか。 - クラスを変更せずに修正するにはどうすればよいですか?
御時間ありがとうございます!