1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
|
#ifndef MOCKPROTECTOR_H
#define MOCKPROTECTOR_H
#include <stdexcept>
#include <cppunit/Protector.h>
class MockProtectorException : public std::runtime_error
{
public:
MockProtectorException()
: std::runtime_error( "MockProtectorException" )
{
}
};
class MockProtector : public CPPUNIT_NS::Protector
{
public:
MockProtector()
: m_wasCalled( false )
, m_wasTrapped( false )
, m_expectException( false )
, m_hasExpectation( false )
, m_shouldPropagateException( false )
{
}
bool protect( const CPPUNIT_NS::Functor &functor,
const CPPUNIT_NS::ProtectorContext &context )
{
try
{
m_wasCalled = true;
return functor();
}
catch ( MockProtectorException & )
{
m_wasTrapped = true;
if ( m_shouldPropagateException )
throw;
reportError( context, CPPUNIT_NS::Message("MockProtector trap") );
}
return false;
}
void setExpectException()
{
m_expectException = true;
m_hasExpectation = true;
}
void setExpectNoException()
{
m_expectException = false;
m_hasExpectation = true;
}
void setExpectCatchAndPropagateException()
{
setExpectException();
m_shouldPropagateException = true;
}
void verify()
{
if ( m_hasExpectation )
{
CPPUNIT_ASSERT_MESSAGE( "MockProtector::protect() was not called",
m_wasCalled );
std::string message;
if ( m_expectException )
message = "did not catch the exception.";
else
message = "caught an unexpected exception.";
CPPUNIT_ASSERT_EQUAL_MESSAGE( "MockProtector::protect() " + message,
m_expectException,
m_wasTrapped );
}
}
private:
bool m_wasCalled;
bool m_wasTrapped;
bool m_expectException;
bool m_hasExpectation;
bool m_shouldPropagateException;
};
#endif // MOCKPROTECTOR_H
|