I am new to Hippomocks and C++. I try to write an Unittest where an exception is catched. For this I have written the following test:
#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()
works correctly, it's an example I found on https://app.assembla.com/wiki/show/hippomocks/Tutorial_3_0.
But if I run test_a()
no exception is thrown and I get the following:
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.
I see that the difference between Foo1 and Foo2 is that in Foo1 the attribute bar is a pointer and in Foo2 it's the value. My questions are:
- Why is there a different behavior? Or rather why is the exception not thrown, since I set
memcpy(&g->bar, b, sizeof(*b))
for the mock-object b? - How can I fix it without changing the classes?
Thanks for your time!