Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Assertion function to check that Exception is thrown

I'm familiar with how the standard C++ assertion works. This has worked well in my project for a variety of testing purposes.

For example, suppose that I want to check that a certain exception is thrown by my code.

Is this possible to do without using a testing framework like CPPUnit?

like image 776
user2054936 Avatar asked Mar 27 '13 20:03

user2054936


People also ask

How do you assert that exception is thrown?

When using JUnit 4, we can simply use the expected attribute of the @Test annotation to declare that we expect an exception to be thrown anywhere in the annotated test method. In this example, we've declared that we're expecting our test code to result in a NullPointerException.

Which assert method is used to validate that a method throws a particular exception or not?

You can use Assert. ThrowsException<T> and Assert.

How do I assert exceptions in MSTest?

There are some complexities to this which will come in another blog post, but the result is we can now use the following syntax to assert an exception in MSTest: Assert. Throws(() => sc. Add("-1"));


1 Answers

You can do the same thing CPPUnit does manually:

bool exceptionThrown = false;

try
{
    // your code
}
catch(ExceptionType&) // special exception type
{
    exceptionThrown = true;
}
catch(...) // or any exception at all
{
    exceptionThrown = true;
}

assert(exceptionThrown); // or whatever else you want to do

Of course, if you use this pattern a lot, it makes sense to use a macro for this.

like image 81
jplatte Avatar answered Oct 07 '22 12:10

jplatte