Menu

unit tests

Anders Widell Mathi Naickan

Introduction

In OpenSAF, we use Google Test for unit testing of c++ source code. A unit test is the smallest level of testing, and the scope of a unit test is one single "unit" - which typically corresponds to one single source code file. If there is a source file called foobar.cc, the corresponding unit tests can be found in the file foobar_test.cc. The tests in foobar_test.cc should only test the code in foobar.cc and foobar.h. If the code in foobar.cc depends on code in other source files, these other objects should be simulated using mock objects.

Unit tests are run on a build server, not on target system. They should not require any special environment to be set up - i.e. it must be possible to run them as an ordinary user (not root) on any modern Linux distribution. They should not requrie OpenSAF to be installed on the system - unit tests are run in the source code tree. And needless to say, it should be possible to run them on any supported architecture (big endian, little endian, 32-bit, 64-bit).

Running the Unit Tests

Here are the steps needed to download googletest, build and run the existing unit tests in OpenSAF:

First go to a directory where you wish to download Google Test, then run the following commands:

Then go to your OpenSAF repo and run "make check"

Writing New Unit Tests

When writing unit tests, follow the Arrange Act Assert pattern. Simply put, this means that you first make some preparations before the test (if necessary), then you do something, and finally you check the result of what you did. Try to have only one single assert per test case.

It is important that unit tests are fast . In particular, this means that you must never sleep in your test cases, or indirectly call any function that may sleep. If the function you are testing may sleep, or if your test depends on some timing, then you should mock the system functions for sleeping and reading the time. Instead of sleeping, you can then step the time in your mock object. If you for some reason want to write a slow unit test (i.e. a unit test that is expected to run for more than a few milliseconds), then please disable the test by default and only enable it if the environment variable OSAF_SLOW_UNITTESTS is set.


Related

Wiki: Home