the Compartmented Robust Posix C++ Unit Test system |
|
---|
Assert that an expression throws the desired exception.
Used in: A test function body, the constructor or destructor of a
fixture, or a function called from
them.
See TEST(name, ...)
.
Requirement: expr;
can be used as a complete
statement.
Requirement: exc_type is either a type, or ....
Requirement: matcher? is an optional parameter. If present it must be one of
what
() string of exceptions derived from
std::exceptionmatch
<matcher>(...) matches the
regular expression to the what
() string of
exceptions derived from std::exception.
The assertion succeeds if, and only if,
the statement expr;
throws an exception that can be caught using
catch(exc_type&), and the caught object matches the
matcher?
argument. The default matcher, if
none is given, matches all exceptions.
On success the test function continues without side effects.
On failure the test is terminated with an error report. The
report includes the expression text, the expression type and,
if the expression caught inherits from std::exception
the output string from the virtual function
std::exception::what()
, or a generic
message otherwise.
See also:
VERIFY_THROW(expr, exc_type, matcher?)
Example: The test program
#include <crpcut.hpp> #include <vector> class int_matcher { int n_, memory_; public: int_matcher(int n) : n_(n), memory_(0) {} bool operator()(int val) { memory_ = val; return val == n_; } friend std::ostream& operator<<(std::ostream &os, const int_matcher &m) { return os << m.memory_ << " does not match the expected " << m.n_; } }; TEST(assert_throw_succeeds) { std::vector<int> v; ASSERT_THROW(v.at(3), std::out_of_range); } TEST(assert_throw_fails) { std::vector<int> v; ASSERT_THROW(v.at(3), std::domain_error); } TEST(assert_throw_with_matcher_fails) { ASSERT_THROW(throw 5, int, int_matcher(3)); } int main(int argc, char *argv[]) { return crpcut::run(argc, argv); }
reports two failed tests:
FAILED!: assert_throw_fails phase="running" -------------------------------------------------------------- samples/assert_throw_fails.cpp:51 ASSERT_THROW(v.at(3), std::domain_error) caught std::exception what()=vector::_M_range_check: __n (which is 3) >= this->size() (which is 0) ------------------------------------------------------------------------------- =============================================================================== FAILED!: assert_throw_with_matcher_fails phase="running" -------------------------------------------------------------- samples/assert_throw_fails.cpp:56 ASSERT_THROW(throw 5, int, int_matcher(3)) 5 does not match the expected 3 does not match 5 ------------------------------------------------------------------------------- =============================================================================== 3 test cases selected Sum Critical Non-critical PASSED : 1 1 0 FAILED : 2 2 0