Qt
Internal/Contributor docs for the Qt SDK. <b>Note:</b> These are NOT official API docs; those are found <a href='https://doc.qt.io/'>here</a>.
Loading...
Searching...
No Matches
qttestlib-tutorial1.qdoc
Go to the documentation of this file.
1// Copyright (C) 2023 The Qt Company Ltd.
2// Copyright (C) 2016 Intel Corporation.
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
4
5/*!
6 \page qttestlib-tutorial1-example.html
7 \previouspage {Qt Test Tutorial}{Qt Test Tutorial Overview}
8 \nextpage {Chapter 2: Data Driven Testing}{Chapter 2}
9
10 \title Chapter 1: Writing a Unit Test
11 \brief How to write a unit test.
12
13 This first chapter demonstrates how to write a simple unit test and how to
14 run the test case as a stand-alone executable.
15
16 \section1 Writing a Test
17
18 Let's assume you want to test the behavior of our QString class.
19 First, you need a class that contains your test functions. This class
20 has to inherit from QObject:
21
22 \snippet tutorial1/testqstring.cpp 0
23
24 \note You need to include the QTest header and declare the test functions as
25 private slots so the test framework finds and executes it.
26
27 Then you need to implement the test function itself. The
28 implementation could look like this:
29
30 \snippet code/doc_src_qtestlib.cpp 8
31
32 The \l QVERIFY() macro evaluates the expression passed as its
33 argument. If the expression evaluates to true, the execution of
34 the test function continues. Otherwise, a message describing the
35 failure is appended to the test log, and the test function stops
36 executing.
37
38 But if you want a more verbose output to the test log, you should
39 use the \l QCOMPARE() macro instead:
40
41 \snippet tutorial1/testqstring.cpp 1
42
43 If the strings are not equal, the contents of both strings are
44 appended to the test log, making it immediately visible why the
45 comparison failed.
46
47 \section1 Preparing the Stand-Alone Executable
48
49 Finally, to make our test case a stand-alone executable, the
50 following two lines are needed:
51
52 \snippet tutorial1/testqstring.cpp 2
53
54 The \l QTEST_MAIN() macro expands to a simple \c main()
55 method that runs all the test functions. Note that if both the
56 declaration and the implementation of our test class are in a \c
57 .cpp file, we also need to include the generated moc file to make
58 Qt's introspection work.
59
60 \section1 Building the Executable
61
62 \include {building-examples.qdocinc} {building the executable} {tutorial1}
63
64 \note If you're using windows, replace \c make with \c
65 nmake or whatever build tool you use.
66
67 \section1 Running the Executable
68
69 Running the resulting executable should give you the following
70 output:
71
72 \snippet code/doc_src_qtestlib.qdoc 10
73
74 Congratulations! You just wrote and executed your first unit test
75 using the Qt Test framework.
76*/