Search code examples
c++unit-testingassert

What is the role of asserts in C++ programs that have unit tests?


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.


Solution

  • 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.