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?
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.
You can use Assert. ThrowsException<T> and Assert.
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"));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With