Enhancement test: catch user-defined exceptions

If I have user-defined exceptions in my code, I cannot get the Boost test to consider them failures.

For instance,

BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES(MyTest,1) BOOST_AUTO_TEST_CASE(MyTest) { // code which throws user defined exception, not derived from std::exception. } 

I get a general message:

 Caught exception: .... unknown location(0):.... 

It does not recognize this error as a failure, since it is not a std :: exception. Therefore, it does not comply with the expected_failures clause.

How to ensure that part of the code always throws an exception? This seems like a useful thing. If the code changes in the future, the code for transmission, and the exception is not thrown, I want to know this.

+4
source share
1 answer

EXPECTED_FAILURES refer to errors regarding BOOST_REQUIRE or other statements. The documentation clearly states:

The function is not intended to check for expected function failures. To verify that a particular input throws an exception , use the BOOST_CHECK_THROW test toolbox.

The emphasis was mine.

Expected failures are intended to be used as a temporary workaround during testing when an assertion fails, but you want to temporarily ignore it.

Taking a fragment from their expected failure characteristics :

 BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES( my_test1, 1 ) BOOST_AUTO_TEST_CASE( my_test1 ) { BOOST_CHECK( 2 == 1 ); } 

will exit

  test.cpp (10): error in "my_test1": check 2 == 1 failed

 Test suite "example" passed with:
   1 assertions out of 1 failed
   1 failures expected
   1 test case out of 1 passed

As you can see, despite the unsuccessful statements, the test case still passed due to the use of the expected failures.


So, if you need to check that something is throwing an exception, you use the following code:

 BOOST_AUTO_TEST_CASE(invalid_operation_should_throw_custom_exception) { MyObj obj; BOOST_REQUIRE_THROW(obj.invalid_operation(), CustomException); } 
+8
source

Source: https://habr.com/ru/post/1310993/


All Articles