1

In a test case I would like to test a function which in debug mode generates an assertion for invalid input. This unfortunately stops Catch test runner. Is there any way to bypass this assertion so that the test runner keeps going ?

Here is my test case:

 SCENARIO("Simple test case", "[tag]") {
    GIVEN("some object") {
        MyObject myobject;

        WHEN("object is initialized with invalid data") {
            // method init generates an assertion when parameters are invalid
            bool result = myObject.init(nullptr, nullptr, nullptr, nullptr);
            REQUIRE(false == result);

            THEN("data processing can't be started") {
            }
        }
    }
}
tommyk
  • 3,187
  • 7
  • 39
  • 61
  • Assertions are there to guard against cases that should *never* happen in a correct program. Why are you unit-testing that ? If invalid parameters may happen within a correct program (from malformed user input, for example), you should use exceptions instead of assertions. – Quentin Sep 20 '16 at 11:54
  • @Quentin In fact it is an external library (generated by Matlab code generator) which I want to test. We generated a wrapper to the generated code but don't really now if the library can handle invalid data which might happen in the real life as they come from input files. I agree that using of exceptions might be a better solution than an asserts in our case. – tommyk Sep 20 '16 at 12:12
  • This seems very similar to http://stackoverflow.com/q/38533272/102345 – JBRWilkinson Sep 21 '16 at 06:12

1 Answers1

1

Usually assert is a macro doing something like

#define assert(e) ((void) ((e) \
  ? 0 
  : (void)printf ("%s:%u: failed assertion `%s'\n",  __FILE__, __LINE__, #e),
    abort(), // <-- this aborts you program after printf's above
    0        
)

and this macro is enabled in debug builds. For more specifics, look into your standard assert.h

So, if you have a binary library against which you link your test cases, you will need to tell the dev team that, unless they gave you a release build with no asserts enabled, you won't be able to unit-test their API for negative test cases.

If you need to test a header-only library or you compile against the source code to be tested, you'll need to

  1. compile your test cases/suite with -DNDEBUG; and/or
  2. define your own assert macro (e,g. to throw an error which you'll catch) and hope that your specific assert.h will test if already defined and won't try to define it again (again, look for specifics in your compiler/std libs assert.h header)
Adrian Colomitchi
  • 3,974
  • 1
  • 14
  • 23