the Compartmented Robust Posix C++ Unit Test system

ASSERT_THROW(expr, exc_type)

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 ....

The assertion succeeds if, and only if, the statement expr; throws an exception that can be caught using catch(exc_type&).

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.

Example: The test program

     
     #include <crpcut.hpp>
     #include <vector>
     
     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);
     }
     
     int main(int argc, char *argv[])
     {
       return crpcut::run(argc, argv);
     }

      

reports one failed test:


     FAILED: assert_throw_fails
     phase="running"  --------------------------------------------------------------
     /home/bjorn/devel/crpcut/doc-src/samples/assert_throw_fails.cpp:40
     ASSERT_THROW(v.at(3), std::domain_error)
       caught std::exception
       what()=vector::_M_range_check
     -------------------------------------------------------------------------------
     ===============================================================================
     Total 2 test cases selected
     UNTESTED : 0
     PASSED   : 1
     FAILED   : 1