Saturday 14 October 2017

TrafficControl: Using Test Fixtures for Unit Tests

For many unit tests, there are some similarities that can be used to reduce some redundant code.

For example, the datamodels for the trafficDataModels (for train, station and track), a pointer to the QML part of the program and the networkControl object.

Google Test offers test fixtures, that makes it possible to setup the same parameters for a set of tests. The test code will be cleaner and each test case will have (more or less) the same setup.


A test fixture is a class where some pointers to some objects are defined.

In SetUp, the data models are defined, a null pointer is set for the QML part and a networkControl object is created.

The TearDown method will free up the allocated memory and clean up the test environment.


The test case is then defined using TEST_F, where the appendix indicates that a test fixture will be used. The test case is networkTest, that was defined above.

In the test case, the networkControl, the needed elements are already defined. The cleanup will be done automatically by TearDown when the test is done.

The concept isn't water-proof, however. The traffic elements (for example trains) has a static int variable to count the total number of trains/stations/tracks. I didn't reset that parameter initially, which caused some test cases to fail. 
  1. Before the first test with the test fixture, that parameter was 0. 
  2. After the first test case, where a train was created, the parameter was set to 1. 
  3. When deleting the train object (called in the networkControl destructor), the static parameter wasn't affected.
  4. In the second test case, the totalNbrOfTrains was 1, but it should have been 0. This caused the test to fail since the test checked the totalNbrOfTrains parameter. 

To fix that issue, the totalNbrOfTrains is set to 0 in the destructor for networkControl.

No comments:

Post a Comment