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. --- uunit.h | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) (limited to 'uunit.h') 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