From ec88915a05a39f2edce5ac01e51f2be971f12b13 Mon Sep 17 00:00:00 2001 From: Bent Bisballe Nyeng Date: Mon, 26 Oct 2020 18:36:28 +0100 Subject: Add assert_throws function for testing expected exception throwing behaviour. --- examples/ExampleTest.cc | 14 +------------- uunit.h | 31 +++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 13 deletions(-) diff --git a/examples/ExampleTest.cc b/examples/ExampleTest.cc index bc5e2f7..2a4997c 100644 --- a/examples/ExampleTest.cc +++ b/examples/ExampleTest.cc @@ -92,19 +92,7 @@ public: void exceptionTests() { - try - { - getBaud(-1); - uUNIT_ASSERT(false); // exception should be thrown for invalid value - } - catch(const bad_speed& e) - { - // Excpected outcome - } - catch(...) - { - uUNIT_ASSERT(false); // Unknown exception were thrown - } + uUNIT_ASSERT_THROWS(bad_speed, getBaud(-1)); } }; diff --git a/uunit.h b/uunit.h index 330ecb6..9c0775d 100644 --- a/uunit.h +++ b/uunit.h @@ -14,6 +14,7 @@ #include #include #include +#include class uUnit { @@ -211,6 +212,36 @@ protected: #define uUNIT_ASSERT_EQUAL(expected, value) \ assert_equal(expected, value, __FILE__, __LINE__) + + template + void assert_throws(const char* expected, std::function expr, + const char* file, std::size_t line) + { + try + { + expr(); + std::ostringstream ss; + ss << "throws assertion failed" << std::endl << + "- Expected: " << expected << " to be thrown" << std::endl << + "- Actual : no exception was thrown" << std::endl; + throw test_result{"", file, line, ss.str()}; + } + catch(const T& t) + { + // T was thrown as expected + } + catch(...) + { + std::ostringstream ss; + ss << "throws assertion failed" << std::endl << + "- Expected: " << expected << " to be thrown" << std::endl << + "- Actual : unexpected exception was thrown" << std::endl; + throw test_result{"", file, line, ss.str()}; + } + } + #define uUNIT_ASSERT_THROWS(expected, expr) \ + assert_throws(#expected, [&](){ expr; }, __FILE__, __LINE__) + private: static std::string sanitize(const std::string& input) { -- cgit v1.2.3