Writing Unittests for Qt4 and KDE4 with QtTestLib

Brad Hards

Sigma Bravo Pty Limited
Abstract

This article provides guidance on writing unittests for Qt4 and KDE4, based on the QtTestLib framework provided with Qt4.1. It provides an introduction to the ideas behind unit testing, tutorial material on the QtTestLib framework, and suggestions for getting the most value for your effort.

This document is matched to Qt 4.1 and KDE 4.


Table of Contents
About Unit Testing
About QtTestLib
Tutorial 1 - A simple test of a date class
Tutorial 2 - Data driven testing of a date class
Tutorial 3 - Testing Graphical User Interfaces
Tutorial 4 - Testing for failure and avoiding tests
Tutorial 5 - Testing Qt slots and signals
Tutorial 6 - Integrating with GNU autoconf
Tutorial 7 - Integrating with qmake
Tutorial 8 - XML output
Alternative tools for testing
Conclusions
Copyright and License

About Unit Testing

A unit test is a test that checks the functionality, behaviour and correctness of a single software component. In Qt4 code (including KDE4 code) unit tests are almost always used to test a single C++ class (although testing a macro or C function is also possible).

Unit tests are a key part of Test Driven Development, however they are useful for all software development processes. It is not essential that all of the code is covered by unit tests (although that is obviously very desirable!). Even a single test is a useful step to improving code quality.

Even if they don't call them "unit tests", most programmers have written some "throwaway" code that they use to check an implementation. If that code was cleaned up a little, and built into the development system, then it could be used over and over to check that the implementation is still OK. To make that work a little easier, we can use test frameworks.

Note that it is sometimes tempting to treat the unit test as a pure verification tool. While it is true that unit tests do help to ensure correct functionality and behaviour, they also assist with other aspects of code quality. Writing a unit test requires a slightly different approach to coding up a class, and thinking about what inputs need to be tested can help to identify logic flaws in the code (even before the tests get run). In addition, the need to make the code testable is a very useful driver to ensure that classes do not suffer from close coupling.

Anyway, enough of the conceptual stuff - lets talk about a specific tool that can reduce some of the effort and let us get on with the job.