I've been adding unit tests to some legacy C++ code, and I've run into many scenarios where an assert inside a function will get tripped during a unit test run. A common idiom that I've run across is functions that take pointer arguments and immediately assert if the argument is NULL.
I could easily get around this by disabling asserts when I'm unit testing. But I'm starting to wonder if unit tests are supposed to alleviate the need for runtime asserts. Is this a correct assessment? Are unit tests supposed to replace runtime asserts by happening sooner in the pipeline (ie: the error is caught in a failing test instead of when the program is running).
On the other hand, I don't like adding soft fails to code (e.g. if (param == NULL) return false;
). A runtime assert at least makes it easier to debug a problem in case a unit test missed a bug.
The Assert section verifies that the action of the method under test behaves as expected. For . NET, methods in the Assert class are often used for verification.
The most scalable way to write unit tests in C is using a unit testing framework, such as: CppUTest. Unity. Google Test.
An assertion is a statement in the Java programming language that enables you to test your assumptions about your program. For example, if you write a method that calculates the speed of a particle, you might assert that the calculated speed is less than the speed of light.
One Assertion in One Test Method To keep unit tests simple, it is best to include a single assertion in one test method. That means, one unit test should test one use-case and no more.
A runtime assert at least makes it easier to debug a problem in case a unit test missed a bug.
This is a pretty fundamental point. Unit tests are not meant to replace assertions (which IMHO are a standard part of producing good quality code), they're meant to complement them.
Secondly, lets say you have a function Foo
which asserts that it's parameters are valid.
In your unit test for Foo
you can make sure you only supply valid parameters, so you think you're alright.
6 months down the track some other developer is going to call Foo
from some new piece of code (which may or may not have unit tests), and at that point you'll be very grateful you put those asserts in there.
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