![]() |
Home |
Files:
In this first chapter we will see how to write a simple unit test for a class, and how to execute it.
Let's assume you want to test the behavior of our QString class. First, you need a class that contains your test functions. This class has to inherit from QObject:
#include <QtTest> class TestQString: public QObject { Q_OBJECT private slots: void toUpper(); };
Note that you need to include the QtTest namespace, and that the test function have to be declared as a private slot so the test framework finds it and can execute it.
Then you need to implement the test function itself. The implementation could look like this:
void TestQString::toUpper() { QString str = "Hello"; VERIFY(str.toUpper()== "HELLO"); }
The VERIFY() macro evaluates the expression passed as its argument. If the expression evaluates to true, the execution of the test function continues. Otherwise, a message describing the failure is appended to the test log, and the test function stops executing.
But if you want a more verbose output to the test log, you should use the COMPARE() macro instead:
void TestQString::toUpper() { QString str = "Hello"; COMPARE(str.toUpper(), QString("HELLO")); }
If the strings are not equal, the contents of both strings is appended to the test log, making it immediately visible why the comparison failed.
Finally, to make our test case a stand-alone executable, the following two lines are needed:
QTTEST_MAIN(TestQString) #include "testqstring.moc"
The QTTEST_MAIN() macro expands to a simple main() method that runs all the test functions. Note that if both the declaration and the implementation of our test class are in a .cpp file, we also need to include the generated moc file to make Qt's introspection work.
Now that we finished writing our test, we want to execute it. Assuming that our test was saved as testqstring.cpp in an empty directory: we build the test using qmake to create a project and generate a makefile.
/myTestDirectory$ qmake -project /myTestDirectory$ qmake /myTestDirectory$ make
Note:If you're using windows, replace make with nmake or whatever build tool you use.
Running the resulting executable should give you the following output:
********* Start testing of TestQString ********* Config: Using QtTest library 2.0.0, Qt 4.0.1 PASS : TestQString::initTestCase() PASS : TestQString::toUpper() PASS : TestQString::cleanupTestCase() Totals: 3 passed, 0 failed, 0 skipped ********* Finished testing of TestQString *********
Congratulations! You just wrote and executed your first unit test using the QtTest framework.
Copyright © 2008 Nokia Corporation and/or its subsidiary(-ies) | Trademarks | Qt Solutions |