1
/****************************************************************************
3
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
4
** Contact: http://www.qt-project.org/legal
6
** This file is part of the documentation of the Qt Toolkit.
8
** $QT_BEGIN_LICENSE:FDL$
9
** Commercial License Usage
10
** Licensees holding valid commercial Qt licenses may use this file in
11
** accordance with the commercial license agreement provided with the
12
** Software or, alternatively, in accordance with the terms contained in
13
** a written agreement between you and Digia. For licensing terms and
14
** conditions see http://qt.digia.com/licensing. For further information
15
** use the contact form at http://qt.digia.com/contact-us.
17
** GNU Free Documentation License Usage
18
** Alternatively, this file may be used under the terms of the GNU Free
19
** Documentation License version 1.3 as published by the Free Software
20
** Foundation and appearing in the file included in the packaging of
21
** this file. Please review the following information to ensure
22
** the GNU Free Documentation License version 1.3 requirements
23
** will be met: http://www.gnu.org/copyleft/fdl.html.
26
****************************************************************************/
29
\page qtest-overview.html
30
\title Qt Test Overview
31
\brief Overview of the Qt unit testing framework.
33
\ingroup frameworks-technologies
34
\ingroup qt-basic-concepts
38
Qt Test is a framework for unit testing Qt based applications and libraries.
40
all the functionality commonly found in unit testing frameworks as
41
well as extensions for testing graphical user interfaces.
43
Qt Test is designed to ease the writing of unit tests for Qt
44
based applications and libraries:
47
\header \li Feature \li Details
50
\li Qt Test consists of about 6000 lines of code and 60
54
\li Qt Test requires only a few symbols from the Qt Core library
57
\li \b {Rapid testing}
58
\li Qt Test needs no special test-runners; no special
59
registration for tests.
61
\li \b {Data-driven testing}
62
\li A test can be executed multiple times with different test data.
64
\li \b {Basic GUI testing}
65
\li Qt Test offers functionality for mouse and keyboard simulation.
68
\li Qt Test supports benchmarking and provides several measurement back-ends.
71
\li Qt Test outputs messages that can be interpreted by Visual
75
\li The error reporting is thread safe and atomic.
78
\li Extensive use of templates prevent errors introduced by
79
implicit type casting.
81
\li \b {Easily extendable}
82
\li Custom types can easily be added to the test data and test output.
85
\section1 Creating a Test
87
To create a test, subclass QObject and add one or more private slots to it. Each
88
private slot is a test function in your test. QTest::qExec() can be used to execute
89
all test functions in the test object.
91
In addition, there are four private slots that are \e not treated as test functions.
92
They will be executed by the testing framework and can be used to initialize and
93
clean up either the entire test or the current test function.
96
\li \c{initTestCase()} will be called before the first test function is executed.
97
\li \c{cleanupTestCase()} will be called after the last test function was executed.
98
\li \c{init()} will be called before each test function is executed.
99
\li \c{cleanup()} will be called after every test function.
102
If \c{initTestCase()} fails, no test function will be executed. If \c{init()} fails,
103
the following test function will not be executed, the test will proceed to the next
107
\snippet code/doc_src_qtestlib.cpp 0
109
For more examples, refer to the \l{Qt Test Tutorial}.
111
\section1 Building a Test
113
If you are using \c qmake as your build tool, just add the
114
following to your project file:
116
\snippet code/doc_src_qtestlib.pro 1
118
If you would like to run the test via \c{make check}, add the
121
\snippet code/doc_src_qtestlib.pro 2
123
See \l{qmake Common Projects#building-a-testcase}{the qmake manual} for
124
more information about \c{make check}.
126
If you are using other build tools, make sure that you add the location
127
of the Qt Test header files to your include path (usually \c{include/QtTest}
128
under your Qt installation directory). If you are using a release build
129
of Qt, link your test to the \c QtTest library. For debug builds, use
132
See \l {Chapter 1: Writing a Unit Test}{Writing a Unit Test} for a step by
135
\section1 Qt Test Command Line Arguments
139
The syntax to execute an autotest takes the following simple form:
141
\snippet code/doc_src_qtestlib.qdoc 2
143
Substitute \c testname with the name of your executable. \c
144
testfunctions can contain names of test functions to be
145
executed. If no \c testfunctions are passed, all tests are run. If you
146
append the name of an entry in \c testdata, the test function will be
147
run only with that test data.
151
\snippet code/doc_src_qtestlib.qdoc 3
153
Runs the test function called \c toUpper with all available test data.
155
\snippet code/doc_src_qtestlib.qdoc 4
157
Runs the \c toUpper test function with all available test data,
158
and the \c toInt test function with the test data called \c
159
zero (if the specified test data doesn't exist, the associated test
162
\snippet code/doc_src_qtestlib.qdoc 5
164
Runs the \c testMyWidget function test, outputs every signal
165
emission and waits 500 milliseconds after each simulated
166
mouse/keyboard event.
170
\section3 Logging Options
172
The following command line options determine how test results are reported:
175
\li \c -o \e{filename,format} \br
176
Writes output to the specified file, in the specified format (one of
177
\c txt, \c xml, \c lightxml or \c xunitxml). The special filename \c -
178
may be used to log to standard output.
179
\li \c -o \e filename \br
180
Writes output to the specified file.
182
Outputs results in plain text.
184
Outputs results as an XML document.
186
Outputs results as a stream of XML tags.
188
Outputs results as an Xunit XML document.
191
The first version of the \c -o option may be repeated in order to log
192
test results in multiple formats, but no more than one instance of this
193
option can log test results to standard output.
195
If the first version of the \c -o option is used, neither the second version
196
of the \c -o option nor the \c -txt, \c -xml, \c -lightxml or \c -xunitxml
197
options should be used.
199
If neither version of the \c -o option is used, test results will be logged to
200
standard output. If no format option is used, test results will be logged in
203
\section3 Test Log Detail Options
205
The following command line options control how much detail is reported
210
Silent output; only shows fatal errors, test failures and minimal status
213
Verbose output; shows when each test function is entered.
214
(This option only affects plain text output.)
216
Extended verbose output; shows each \l QCOMPARE() and \l QVERIFY().
217
(This option affects all output formats and implies \c -v1 for plain text output.)
219
Shows all signals that get emitted and the slot invocations resulting from
221
(This option affects all output formats.)
224
\section3 Testing Options
226
The following command-line options influence how tests are run:
229
\li \c -functions \br
230
Outputs all test functions available in the test, then quits.
232
Outputs all data tags available in the test.
233
A global data tag is preceded by ' __global__ '.
234
\li \c -eventdelay \e ms \br
235
If no delay is specified for keyboard or mouse simulation
236
(\l QTest::keyClick(),
237
\l QTest::mouseClick() etc.), the value from this parameter
238
(in milliseconds) is substituted.
239
\li \c -keydelay \e ms \br
240
Like -eventdelay, but only influences keyboard simulation and not mouse
242
\li \c -mousedelay \e ms \br
243
Like -eventdelay, but only influences mouse simulation and not keyboard
245
\li \c -maxwarnings \e number \br
246
Sets the maximum number of warnings to output. 0 for unlimited, defaults to
248
\li \c -nocrashhandler \br
249
Disables the crash handler on Unix platforms.
252
\section3 Benchmarking Options
254
The following command line options control benchmark testing:
257
\li \c -callgrind \br
258
Uses Callgrind to time benchmarks (Linux only).
259
\li \c -tickcounter \br
260
Uses CPU tick counters to time benchmarks.
261
\li \c -eventcounter \br
262
Counts events received during benchmarks.
263
\li \c -minimumvalue \e n \br
264
Sets the minimum acceptable measurement value.
265
\li \c -iterations \e n \br
266
Sets the number of accumulation iterations.
267
\li \c -median \e n \br
268
Sets the number of median iterations.
270
Outputs verbose benchmarking information.
273
\section3 Miscellaneous Options
277
Outputs the possible command line arguments and gives some useful help.
280
\section1 Creating a Benchmark
282
To create a benchmark, follow the instructions for creating a test and then add a
283
QBENCHMARK macro to the test function that you want to benchmark.
285
\snippet code/doc_src_qtestlib.cpp 12
287
The code inside the QBENCHMARK macro will be measured, and possibly also repeated
288
several times in order to get an accurate measurement. This depends on the selected
289
measurement back-end. Several back-ends are available. They can be selected on the
292
\target testlib-benchmarking-measurement
296
\li Command-line Argument
301
\row \li CPU tick counter
303
\li Windows, Mac OS X, Linux, many UNIX-like systems.
304
\row \li Valgrind Callgrind
306
\li Linux (if installed)
307
\row \li Event Counter
312
In short, walltime is always available but requires many repetitions to
314
Tick counters are usually available and can provide
315
results with fewer repetitions, but can be susceptible to CPU frequency
317
Valgrind provides exact results, but does not take
318
I/O waits into account, and is only available on a limited number of
320
Event counting is available on all platforms and it provides the number of events
321
that were received by the event loop before they are sent to their corresponding
322
targets (this might include non-Qt events).
324
\note Depending on the device configuration, tick counters on the
325
Windows CE platform may not be as fine-grained, compared to other platforms.
326
Devices that do not support high-resolution timers default to
327
one-millisecond granularity.
329
See \l {Chapter 5: Writing a Benchmark}{Writing a Benchmark} in the Qt Test
330
Tutorial for more benchmarking examples.
332
\section1 Using Qt Test Remotely on Windows CE
334
The \c cetest convenience application enables you to launch an
335
application remotely on a Windows CE device or emulator.
337
It needs to be executed after the unit test has been successfully compiled.
339
Prior to launching, the following files are copied to the device:
342
\li all Qt libraries the project links to
343
\li \l {QtRemote}{QtRemote.dll}
344
\li the c runtime library specified during installation
345
\li all files specified in the \c .pro file following the \l DEPLOYMENT rules.
349
The syntax to execute an autotest takes the following simple form:
351
\snippet code/doc_src_qtestlib.qdoc 6
354
\c cetest provides the same options as those for unit-testing on non cross-compiled
355
platforms. See \l {Qt Test Command Line Arguments} {Command Line Arguments} for
358
The following commands are also included:
362
Compiles the test version in debug mode.
364
Compiles the test version in release mode.
365
\li \c -libpath \e path \br
366
Copies Qt libraries to the specified path.
367
\li \c -qt-delete \br
368
Deletes Qt libraries after execution.
369
\li \c -project-delete \br
370
Deletes project files after execution.
372
Deletes project and Qt libraries after execution.
374
Specifies a qt.conf file to be deployed to remote directory.
377
\note \c{debug} is the default build option.
380
\c QtRemote is a small library which is built after Qt Test. It allows the host
381
system to create a process on a remote device and waits until its execution has
384
\section2 Requirements
385
\c cetest uses Microsoft ActiveSync to establish a remote connection between the
386
host computer and the device. Thus header files and libraries are needed to compile
387
cetest and QtRemote successfully.
389
Prior to \l{Installing Qt for Windows CE}{installation} of Qt, you need to set your
390
\c INCLUDE and \c LIB environment variables properly.
392
A default installation of Windows Mobile 5 for Pocket PC can be obtained by:
394
\snippet code/doc_src_qtestlib.qdoc 7
396
Note that Qt will remember the path, so you do not need to set it again
397
after switching the environments for cross-compilation.
399
\section1 3rd Party Code
401
The CPU tick counters used for benchmarking are licensed under the following
402
license: (from src/testlib/3rdparty/cycle.h)
405
Copyright (c) 2003, 2006 Matteo Frigo\br
406
Copyright (c) 2003, 2006 Massachusetts Institute of Technology
408
Permission is hereby granted, free of charge, to any person obtaining
409
a copy of this software and associated documentation files (the
410
"Software"), to deal in the Software without restriction, including
411
without limitation the rights to use, copy, modify, merge, publish,
412
distribute, sublicense, and/or sell copies of the Software, and to
413
permit persons to whom the Software is furnished to do so, subject to
414
the following conditions:
416
The above copyright notice and this permission notice shall be
417
included in all copies or substantial portions of the Software.
419
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
420
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
421
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
422
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
423
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
424
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
425
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
430
\page qtest-tutorial.html
431
\brief A short introduction to testing with Qt Test.
432
\contentspage Qt Test Overview
433
\nextpage {Chapter 1: Writing a Unit Test}{Chapter 1}
434
\ingroup best-practices
436
\title Qt Test Tutorial
438
This tutorial gives a short introduction to how to use some of the
439
features of the Qt Test framework. It is divided into five
443
\li \l {Chapter 1: Writing a Unit Test}{Writing a Unit Test}
444
\li \l {Chapter 2: Data Driven Testing}{Data Driven Testing}
445
\li \l {Chapter 3: Simulating GUI Events}{Simulating GUI Events}
446
\li \l {Chapter 4: Replaying GUI Events}{Replaying GUI Events}
447
\li \l {Chapter 5: Writing a Benchmark}{Writing a Benchmark}
456
\contentspage {Qt Test Tutorial}{Contents}
457
\nextpage {Chapter 2: Data Driven Testing}{Chapter 2}
459
\title Chapter 1: Writing a Unit Test
461
In this first chapter we will see how to write a simple unit test
462
for a class, and how to execute it.
464
\section1 Writing a Test
466
Let's assume you want to test the behavior of our QString class.
467
First, you need a class that contains your test functions. This class
468
has to inherit from QObject:
470
\snippet tutorial1/testqstring.cpp 0
472
\note You need to include the QTest header and declare the test functions as
473
private slots so the test framework finds and executes it.
475
Then you need to implement the test function itself. The
476
implementation could look like this:
478
\snippet code/doc_src_qtestlib.cpp 8
480
The \l QVERIFY() macro evaluates the expression passed as its
481
argument. If the expression evaluates to true, the execution of
482
the test function continues. Otherwise, a message describing the
483
failure is appended to the test log, and the test function stops
486
But if you want a more verbose output to the test log, you should
487
use the \l QCOMPARE() macro instead:
489
\snippet tutorial1/testqstring.cpp 1
491
If the strings are not equal, the contents of both strings are
492
appended to the test log, making it immediately visible why the
495
Finally, to make our test case a stand-alone executable, the
496
following two lines are needed:
498
\snippet tutorial1/testqstring.cpp 2
500
The \l QTEST_MAIN() macro expands to a simple \c main()
501
method that runs all the test functions. Note that if both the
502
declaration and the implementation of our test class are in a \c
503
.cpp file, we also need to include the generated moc file to make
504
Qt's introspection work.
506
\section1 Executing a Test
508
Now that we finished writing our test, we want to execute
509
it. Assuming that our test was saved as \c testqstring.cpp in an
510
empty directory, we build the test using qmake to create a project
511
and generate a makefile.
513
\snippet code/doc_src_qtestlib.qdoc 9
515
\note If you're using windows, replace \c make with \c
516
nmake or whatever build tool you use.
518
Running the resulting executable should give you the following
521
\snippet code/doc_src_qtestlib.qdoc 10
523
Congratulations! You just wrote and executed your first unit test
524
using the Qt Test framework.
530
\previouspage {Chapter 1: Writing a Unit Test}{Chapter 1}
531
\contentspage {Qt Test Tutorial}{Contents}
532
\nextpage {Chapter 3: Simulating Gui Events}{Chapter 3}
534
\title Chapter 2: Data Driven Testing
536
In this chapter we will demonstrate how to execute a test
537
multiple times with different test data.
539
So far, we have hard coded the data we wanted to test into our
540
test function. If we add more test data, the function might look like
543
\snippet code/doc_src_qtestlib.cpp 11
545
To prevent that the function ends up being cluttered by repetitive
546
code, Qt Test supports adding test data to a test function. All
547
we need is to add another private slot to our test class:
549
\snippet tutorial2/testqstring.cpp 0
551
\section1 Writing the Data Function
553
A test function's associated data function carries the same name,
554
appended by \c{_data}. Our data function looks like this:
556
\snippet tutorial2/testqstring.cpp 1
558
First, we define the two elements of our test table using the \l
559
QTest::addColumn() function: a test string, and the
560
expected result of applying the QString::toUpper() function to
563
Then we add some data to the table using the \l
564
QTest::newRow() function. Each set of data will become a
565
separate row in the test table.
567
\l QTest::newRow() takes one argument: a name that will be
568
associated with the data set. If the test fails, the name will be
569
used in the test log, referencing the failed data. Then we
570
stream the data set into the new table row. First an arbitrary
571
string, and then the expected result of applying the
572
QString::toUpper() function to that string.
574
You can think of the test data as a two-dimensional table. In
575
our case, it has two columns called \c string and \c result and
576
three rows. In addition a name as well as an index is associated
602
\section1 Rewriting the Test Function
604
Our test function can now be rewritten:
606
\snippet tutorial2/testqstring.cpp 2
608
The TestQString::toUpper() function will be executed three times,
609
once for each entry in the test table that we created in the
610
associated TestQString::toUpper_data() function.
612
First, we fetch the two elements of the data set using the \l
613
QFETCH() macro. \l QFETCH() takes two arguments: The data type of
614
the element and the element name. Then we perform the test using
615
the \l QCOMPARE() macro.
617
This approach makes it very easy to add new data to the test
618
without modifying the test itself.
620
And again, to make our test case a stand-alone executable,
621
the following two lines are needed:
623
\snippet tutorial2/testqstring.cpp 3
625
As before, the QTEST_MAIN() macro expands to a simple main()
626
method that runs all the test functions, and since both the
627
declaration and the implementation of our test class are in a .cpp
628
file, we also need to include the generated moc file to make Qt's
635
\previouspage {Chapter 2: Data Driven Testing}{Chapter 2}
636
\contentspage {Qt Test Tutorial}{Contents}
637
\nextpage {Chapter 4: Replaying GUI Events}{Chapter 4}
639
\title Chapter 3: Simulating GUI Events
641
Qt Test features some mechanisms to test graphical user
642
interfaces. Instead of simulating native window system events,
643
Qt Test sends internal Qt events. That means there are no
644
side-effects on the machine the tests are running on.
646
In this chapter we will see how to write a simple GUI test.
648
\section1 Writing a GUI test
650
This time, let's assume you want to test the behavior of our
651
QLineEdit class. As before, you will need a class that contains
654
\snippet tutorial3/testgui.cpp 0
656
The only difference is that you need to include the QtGui class
657
definitions in addition to the QTest namespace.
659
\snippet tutorial3/testgui.cpp 1
661
In the implementation of the test function we first create a
662
QLineEdit. Then we simulate writing "hello world" in the line edit
663
using the \l QTest::keyClicks() function.
665
\note The widget must also be shown in order to correctly test keyboard
668
QTest::keyClicks() simulates clicking a sequence of keys on a
669
widget. Optionally, a keyboard modifier can be specified as well
670
as a delay (in milliseconds) of the test after each key click. In
671
a similar way, you can use the QTest::keyClick(),
672
QTest::keyPress(), QTest::keyRelease(), QTest::mouseClick(),
673
QTest::mouseDClick(), QTest::mouseMove(), QTest::mousePress()
674
and QTest::mouseRelease() functions to simulate the associated
677
Finally, we use the \l QCOMPARE() macro to check if the line edit's
680
As before, to make our test case a stand-alone executable, the
681
following two lines are needed:
683
\snippet tutorial3/testgui.cpp 2
685
The QTEST_MAIN() macro expands to a simple main() method that
686
runs all the test functions, and since both the declaration and
687
the implementation of our test class are in a .cpp file, we also
688
need to include the generated moc file to make Qt's introspection
695
\previouspage {Chapter 3: Simulating GUI Events}{Chapter 3}
696
\contentspage {Qt Test Tutorial}{Contents}
697
\nextpage {Chapter 5: Writing a Benchmark}{Chapter 5}
699
\title Chapter 4: Replaying GUI Events
701
In this chapter, we will show how to simulate a GUI event,
702
and how to store a series of GUI events as well as replay them on
705
The approach to storing a series of events and replaying them is
706
quite similar to the approach explained in \l {Chapter 2:
707
Data Driven Testing}{chapter 2}. All you need to do is to add a data
708
function to your test class:
710
\snippet tutorial4/testgui.cpp 0
712
\section1 Writing the Data Function
714
As before, a test function's associated data function carries the
715
same name, appended by \c{_data}.
717
\snippet tutorial4/testgui.cpp 1
719
First, we define the elements of the table using the
720
QTest::addColumn() function: A list of GUI events, and the
721
expected result of applying the list of events on a QWidget. Note
722
that the type of the first element is \l QTestEventList.
724
A QTestEventList can be populated with GUI events that can be
725
stored as test data for later usage, or be replayed on any
728
In our current data function, we create two \l
729
{QTestEventList} elements. The first list consists of a single click to
730
the 'a' key. We add the event to the list using the
731
QTestEventList::addKeyClick() function. Then we use the
732
QTest::newRow() function to give the data set a name, and
733
stream the event list and the expected result into the table.
735
The second list consists of two key clicks: an 'a' with a
736
following 'backspace'. Again we use the
737
QTestEventList::addKeyClick() to add the events to the list, and
738
QTest::newRow() to put the event list and the expected
739
result into the table with an associated name.
741
\section1 Rewriting the Test Function
743
Our test can now be rewritten:
745
\snippet tutorial4/testgui.cpp 2
747
The TestGui::testGui() function will be executed two times,
748
once for each entry in the test data that we created in the
749
associated TestGui::testGui_data() function.
751
First, we fetch the two elements of the data set using the \l
752
QFETCH() macro. \l QFETCH() takes two arguments: the data type of
753
the element and the element name. Then we create a QLineEdit, and
754
apply the list of events on that widget using the
755
QTestEventList::simulate() function.
757
Finally, we use the QCOMPARE() macro to check if the line edit's
760
As before, to make our test case a stand-alone executable,
761
the following two lines are needed:
763
\snippet tutorial4/testgui.cpp 3
765
The QTEST_MAIN() macro expands to a simple main() method that
766
runs all the test functions, and since both the declaration and
767
the implementation of our test class are in a .cpp file, we also
768
need to include the generated moc file to make Qt's introspection
775
\previouspage {Chapter 4: Replaying GUI Events}{Chapter 4}
776
\contentspage {Qt Test Tutorial}{Contents}
778
\title Chapter 5: Writing a Benchmark
780
In this final chapter we will demonstrate how to write benchmarks
783
\section1 Writing a Benchmark
784
To create a benchmark we extend a test function with a QBENCHMARK macro.
785
A benchmark test function will then typically consist of setup code and
786
a QBENCHMARK macro that contains the code to be measured. This test
787
function benchmarks QString::localeAwareCompare().
789
\snippet tutorial5/benchmarking.cpp 0
791
Setup can be done at the beginning of the function, the clock is not
792
running at this point. The code inside the QBENCHMARK macro will be
793
measured, and possibly repeated several times in order to get an
794
accurate measurement.
796
Several \l {testlib-benchmarking-measurement}{back-ends} are available
797
and can be selected on the command line.
799
\section1 Data Functions
801
Data functions are useful for creating benchmarks that compare
802
multiple data inputs, for example locale aware compare against standard
805
\snippet tutorial5/benchmarking.cpp 1
807
The test function then uses the data to determine what to benchmark.
809
\snippet tutorial5/benchmarking.cpp 2
811
The "if (useLocaleCompare)" switch is placed outside the QBENCHMARK
812
macro to avoid measuring its overhead. Each benchmark test function
813
can have one active QBENCHMARK macro.
815
\section1 External Tools
817
Tools for handling and visualizing test data are available as part of
818
the \l {qtestlib-tools} project.
819
These include a tool for comparing performance data obtained from test
820
runs and a utility to generate Web-based graphs of performance data.
822
See the \l{qtestlib-tools Announcement}{qtestlib-tools announcement}
823
for more information on these tools and a simple graphing example.