我是 Hippomocks 和 C++ 的新手。我尝试编写一个捕获异常的单元测试。为此,我编写了以下测试:
#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 中,属性栏是一个指针,而在 Foo2 中,它是值。我的问题是:
- 为什么会有不同的行为?或者更确切地说,为什么没有抛出异常,因为我
memcpy(&g->bar, b, sizeof(*b))
为模拟对象 b 设置了? - 如何在不更改课程的情况下修复它?
谢谢你的时间!