diff options
author | Bent Bisballe Nyeng <deva@aasimon.org> | 2020-10-26 18:36:28 +0100 |
---|---|---|
committer | Bent Bisballe Nyeng <deva@aasimon.org> | 2020-10-26 19:50:41 +0100 |
commit | ec88915a05a39f2edce5ac01e51f2be971f12b13 (patch) | |
tree | 5aa38dd20d828e8856a1020f6b7e6d43be4b4014 | |
parent | 2b347407b1157086b58ae9d897e14b77fbdce5b4 (diff) |
Add assert_throws function for testing expected exception throwing behaviour.
-rw-r--r-- | examples/ExampleTest.cc | 14 | ||||
-rw-r--r-- | 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)); } }; @@ -14,6 +14,7 @@ #include <fstream> #include <cmath> #include <exception> +#include <typeinfo> class uUnit { @@ -211,6 +212,36 @@ protected: #define uUNIT_ASSERT_EQUAL(expected, value) \ assert_equal(expected, value, __FILE__, __LINE__) + + template<typename T> + void assert_throws(const char* expected, std::function<void()> 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>(#expected, [&](){ expr; }, __FILE__, __LINE__) + private: static std::string sanitize(const std::string& input) { |