Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 569
lhumongous Avatar asked Apr 07 '10 20:04

lhumongous


People also ask

What is the purpose of an assert in a unit test?

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.

What can be used for unit testing in C?

The most scalable way to write unit tests in C is using a unit testing framework, such as: CppUTest. Unity. Google Test.

What is an assert in programming?

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.

How many asserts are in a test case?

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.


1 Answers

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.

like image 143
Orion Edwards Avatar answered Oct 20 '22 10:10

Orion Edwards