Skip to content

Commit

Permalink
Merge pull request #48 from dampsoft/assert-throws-better-description
Browse files Browse the repository at this point in the history
If we catch an unexpected exception in AssertThrows,
print the description of the exception.
  • Loading branch information
sbeyer authored Feb 26, 2020
2 parents 7794533 + 78f6b96 commit aaf8480
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
13 changes: 13 additions & 0 deletions example/exceptions_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,14 @@ struct ClassWithExceptions
}
};

struct ExpectedException : public std::exception
{
const char* what() const throw()
{
return "Description of the exception we expected";
}
};

void ExceptionTests()
{
ClassWithExceptions objectUnderTest;
Expand Down Expand Up @@ -89,4 +97,9 @@ void ExceptionTests()
AssertThrows(AssertionException, LastException<std::logic_error>());
AssertThat(LastException<AssertionException>().GetMessage(), Contains("No exception was stored"));
}

it("prints description of unwanted exception");
{
AssertTestFails(AssertThrows(ExpectedException, objectUnderTest.LogicError()), "Expected ExpectedException. Wrong exception was thrown. Description of unwanted exception: not logical!");
}
}
13 changes: 13 additions & 0 deletions include/snowhouse/exceptions.h
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ namespace snowhouse
SNOWHOUSE_TEMPVAR(storage).compiler_thinks_i_am_unused(); \
bool SNOWHOUSE_TEMPVAR(wrong_exception) = false; \
bool SNOWHOUSE_TEMPVAR(no_exception) = false; \
bool SNOWHOUSE_TEMPVAR(more_info) = true; \
std::string SNOWHOUSE_TEMPVAR(info_string); \
try \
{ \
METHOD; \
Expand All @@ -97,6 +99,14 @@ namespace snowhouse
catch (...) \
{ \
SNOWHOUSE_TEMPVAR(wrong_exception) = true; \
if (auto eptr = std::current_exception()) { \
try { \
std::rethrow_exception(eptr); \
} catch (const std::exception& e) { \
SNOWHOUSE_TEMPVAR(more_info) = true; \
SNOWHOUSE_TEMPVAR(info_string) = e.what(); \
} catch (...) {} \
} \
} \
if (SNOWHOUSE_TEMPVAR(no_exception)) \
{ \
Expand All @@ -108,6 +118,9 @@ namespace snowhouse
{ \
::std::ostringstream SNOWHOUSE_TEMPVAR(stm); \
SNOWHOUSE_TEMPVAR(stm) << "Expected " #EXCEPTION_TYPE ". Wrong exception was thrown."; \
if (SNOWHOUSE_TEMPVAR(more_info)) { \
SNOWHOUSE_TEMPVAR(stm) << " Description of unwanted exception: " << SNOWHOUSE_TEMPVAR(info_string); \
} \
::snowhouse::ConfigurableAssert<FAILURE_HANDLER_TYPE>::Failure(SNOWHOUSE_TEMPVAR(stm).str()); \
} \
do {} while (false)
Expand Down

0 comments on commit aaf8480

Please sign in to comment.