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