QTest Namespace | Qt Test | Qt 6.10.3
Description: The QTest namespace contains all the functions and declarations that are related to Qt Test.

- Qt 6.10
- Qt Test
- QTest Namespace
- Qt 6.10.3 Reference Documentation

# QTest Namespace

The QTest namespace contains all the functions and declarations that are related to Qt Test. More...

Header: | `#include <QTest>`
CMake: | `find_package(Qt6 REQUIRED COMPONENTS Test)` `target_link_libraries(mytarget PRIVATE Qt6::Test)`
qmake: | `QT += testlib`

- Deprecated members

## Classes

class | QTouchEventSequence
class | QTouchEventWidgetSequence
`(since 6.8)` class | ThrowOnFailDisabler
`(since 6.8)` class | ThrowOnFailEnabler
`(since 6.8)` class | ThrowOnSkipDisabler
`(since 6.8)` class | ThrowOnSkipEnabler

## Types

enum | KeyAction { Press, Release, Click, Shortcut }
enum | MouseAction { MousePress, MouseRelease, MouseClick, MouseDClick, MouseMove }
enum | QBenchmarkMetric { FramesPerSecond, BitsPerSecond, BytesPerSecond, WalltimeMilliseconds, WalltimeNanoseconds, …, EmulationFaults }
enum | TestFailMode { Abort, Continue }

## Functions

void | addColumn(const char *name, T *dummy = 0)
QTestData & | addRow(const char *format, ...)
const char * | benchmarkMetricName(QTest::QBenchmarkMetric metric)
const char * | benchmarkMetricUnit(QTest::QBenchmarkMetric metric)
QPointingDevice * | createTouchDevice(QInputDevice::DeviceType devType = QInputDevice::DeviceType::TouchScreen, QInputDevice::Capabilities caps = QInputDevice::Capability::Position)
const char * | currentAppName()
const char * | currentDataTag()
bool | currentTestFailed()
const char * | currentTestFunction()
`(since 6.5)` bool | currentTestResolved()
`(since 6.3)` void | failOnWarning(const QRegularExpression &messagePattern)
`(since 6.8)` void | failOnWarning()
`(since 6.3)` void | failOnWarning(const char *message)
void | ignoreMessage(QtMsgType type, const char *message)
void | ignoreMessage(QtMsgType type, const QRegularExpression &messagePattern)
void | keyClick(QWidget *widget, Qt::Key key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)
void | keyClick(QWidget *widget, char key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)
void | keyClick(QWindow *window, Qt::Key key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)
void | keyClick(QWindow *window, char key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)
void | keyClicks(QWidget *widget, const QString &sequence, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)
void | keyEvent(QTest::KeyAction action, QWidget *widget, Qt::Key key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)
void | keyEvent(QTest::KeyAction action, QWidget *widget, char ascii, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)
void | keyEvent(QTest::KeyAction action, QWindow *window, Qt::Key key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)
void | keyEvent(QTest::KeyAction action, QWindow *window, char ascii, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)
void | keyPress(QWidget *widget, Qt::Key key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)
void | keyPress(QWidget *widget, char key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)
void | keyPress(QWindow *window, Qt::Key key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)
void | keyPress(QWindow *window, char key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)
void | keyRelease(QWidget *widget, Qt::Key key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)
void | keyRelease(QWidget *widget, char key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)
void | keyRelease(QWindow *window, Qt::Key key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)
void | keyRelease(QWindow *window, char key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)
void | keySequence(QWidget *widget, const QKeySequence &keySequence)
void | keySequence(QWindow *window, const QKeySequence &keySequence)
void | mouseClick(QWidget *widget, Qt::MouseButton button, Qt::KeyboardModifiers modifier = Qt::KeyboardModifiers(), QPoint pos = QPoint(), int delay = -1)
void | mouseClick(QWindow *window, Qt::MouseButton button, Qt::KeyboardModifiers stateKey = Qt::KeyboardModifiers(), QPoint pos = QPoint(), int delay = -1)
void | mouseDClick(QWidget *widget, Qt::MouseButton button, Qt::KeyboardModifiers modifier = Qt::KeyboardModifiers(), QPoint pos = QPoint(), int delay = -1)
void | mouseDClick(QWindow *window, Qt::MouseButton button, Qt::KeyboardModifiers stateKey = Qt::KeyboardModifiers(), QPoint pos = QPoint(), int delay = -1)
void | mouseMove(QWidget *widget, QPoint pos = QPoint(), int delay = -1)
void | mouseMove(QWindow *window, QPoint pos = QPoint(), int delay = -1)
void | mousePress(QWidget *widget, Qt::MouseButton button, Qt::KeyboardModifiers modifier = Qt::KeyboardModifiers(), QPoint pos = QPoint(), int delay = -1)
void | mousePress(QWindow *window, Qt::MouseButton button, Qt::KeyboardModifiers stateKey = Qt::KeyboardModifiers(), QPoint pos = QPoint(), int delay = -1)
void | mouseRelease(QWidget *widget, Qt::MouseButton button, Qt::KeyboardModifiers modifier = Qt::KeyboardModifiers(), QPoint pos = QPoint(), int delay = -1)
void | mouseRelease(QWindow *window, Qt::MouseButton button, Qt::KeyboardModifiers stateKey = Qt::KeyboardModifiers(), QPoint pos = QPoint(), int delay = -1)
QTestData & | newRow(const char *dataTag)
int | qExec(QObject *testObject, int argc = 0, char **argv = nullptr)
int | qExec(QObject *testObject, const QStringList &arguments)
QSharedPointer<QTemporaryDir> | qExtractTestData(const QString &dirName)
`(since 6.5)` void | qRegisterTestCase(const QString &name, QTest::TestEntryFunction entryFunction)
`(since 6.7)` void | qSleep(std::chrono::milliseconds msecs)
void | qSleep(int ms)
`(since 6.7)` void | qWait(std::chrono::milliseconds msecs)
void | qWait(int msecs)
`(since 6.7)` bool | qWaitFor(Functor predicate, QDeadlineTimer deadline = QDeadlineTimer(Internal::defaultTryTimeout))
bool | qWaitFor(Functor predicate, int timeout)
`(since 6.10)` bool | qWaitForWindowActive(QWidget *widget, QDeadlineTimer timeout)
`(since 6.10)` bool | qWaitForWindowActive(QWindow *window, QDeadlineTimer timeout)
`(since 6.10)` bool | qWaitForWindowActive(QWidget *widget)
`(since 6.10)` bool | qWaitForWindowActive(QWindow *window)
bool | qWaitForWindowActive(QWidget *widget, int timeout)
bool | qWaitForWindowActive(QWindow *window, int timeout)
`(since 6.10)` bool | qWaitForWindowExposed(QWidget *widget, QDeadlineTimer timeout)
`(since 6.10)` bool | qWaitForWindowExposed(QWindow *window, QDeadlineTimer timeout)
`(since 6.10)` bool | qWaitForWindowExposed(QWidget *widget)
`(since 6.10)` bool | qWaitForWindowExposed(QWindow *window)
bool | qWaitForWindowExposed(QWidget *widget, int timeout)
bool | qWaitForWindowExposed(QWindow *window, int timeout)
`(since 6.7)` bool | qWaitForWindowFocused(QWidget *widget, QDeadlineTimer timeout)
`(since 6.7)` bool | qWaitForWindowFocused(QWindow *window, QDeadlineTimer timeout)
`(since 6.10)` bool | qWaitForWindowFocused(QWidget *widget)
`(since 6.10)` bool | qWaitForWindowFocused(QWindow *window)
void | setBenchmarkResult(qreal result, QTest::QBenchmarkMetric metric)
`(since 6.8)` void | setThrowOnFail(bool enable)
`(since 6.8)` void | setThrowOnSkip(bool enable)
char * | toHexRepresentation(const char *ba, qsizetype length)
char * | toString(QSizePolicy sp)
char * | toString(const T &value)
char * | toString(QSizePolicy::ControlType ct)
char * | toString(QSizePolicy::ControlTypes cts)
char * | toString(QSizePolicy::Policy p)
char * | toString(const QByteArray &ba)
char * | toString(const QCborError &c)
char * | toString(const QChar &character)
char * | toString(const QDate &date)
char * | toString(const QDateTime &dateTime)
`(since 6.5)` char * | toString(const QKeySequence &ks)
char * | toString(const QLatin1StringView &string)
char * | toString(const QPoint &point)
char * | toString(const QPointF &point)
char * | toString(const QRect &rectangle)
char * | toString(const QRectF &rectangle)
char * | toString(const QSize &size)
char * | toString(const QSizeF &size)
char * | toString(const QString &string)
char * | toString(const QStringView &string)
char * | toString(const QTime &time)
char * | toString(const QUrl &url)
char * | toString(const QUuid &uuid)
char * | toString(const QVariant &variant)
char * | toString(const QVector2D &v)
char * | toString(const QVector3D &v)
char * | toString(const QVector4D &v)
char * | toString(const std::pair<T1, T2> &pair)
char * | toString(const std::tuple<Types...> &tuple)
char * | toString(std::nullptr_t)
QTest::QTouchEventWidgetSequence | touchEvent(QWidget *widget, QPointingDevice *device, bool autoCommit = true)
QTest::QTouchEventSequence | touchEvent(QWindow *window, QPointingDevice *device, bool autoCommit = true)
`(since 6.8)` void | wheelEvent(QWindow *window, QPointF pos, QPoint angleDelta, QPoint pixelDelta = QPoint(0, 0), Qt::KeyboardModifiers stateKey = Qt::NoModifier, Qt::ScrollPhase phase = Qt::NoScrollPhase)

## Macros

| QBENCHMARK
| QBENCHMARK_ONCE
| QCOMPARE(actual, expected)
`(since 6.9)` | QCOMPARE_3WAY(lhs, rhs, order)
`(since 6.4)` | QCOMPARE_EQ(computed, baseline)
`(since 6.4)` | QCOMPARE_GE(computed, baseline)
`(since 6.4)` | QCOMPARE_GT(computed, baseline)
`(since 6.4)` | QCOMPARE_LE(computed, baseline)
`(since 6.4)` | QCOMPARE_LT(computed, baseline)
`(since 6.4)` | QCOMPARE_NE(computed, baseline)
| QEXPECT_FAIL(dataIndex, comment, mode)
| QFAIL(message)
| QFETCH(type, name)
| QFETCH_GLOBAL(type, name)
| QFINDTESTDATA(filename)
| QSKIP(description)
| QTEST(actual, testElement)
| QTEST_APPLESS_MAIN(TestClass)
| QTEST_GUILESS_MAIN(TestClass)
| QTEST_MAIN(TestClass)
`(since 6.8)` | QTEST_THROW_ON_FAIL
`(since 6.8)` | QTEST_THROW_ON_SKIP
| QTRY_COMPARE(actual, expected)
`(since 6.4)` | QTRY_COMPARE_EQ(computed, baseline)
`(since 6.4)` | QTRY_COMPARE_EQ_WITH_TIMEOUT(computed, baseline, timeout)
`(since 6.4)` | QTRY_COMPARE_GE(computed, baseline)
`(since 6.4)` | QTRY_COMPARE_GE_WITH_TIMEOUT(computed, baseline, timeout)
`(since 6.4)` | QTRY_COMPARE_GT(computed, baseline)
`(since 6.4)` | QTRY_COMPARE_GT_WITH_TIMEOUT(computed, baseline, timeout)
`(since 6.4)` | QTRY_COMPARE_LE(computed, baseline)
`(since 6.4)` | QTRY_COMPARE_LE_WITH_TIMEOUT(computed, baseline, timeout)
`(since 6.4)` | QTRY_COMPARE_LT(computed, baseline)
`(since 6.4)` | QTRY_COMPARE_LT_WITH_TIMEOUT(computed, baseline, timeout)
`(since 6.4)` | QTRY_COMPARE_NE(computed, baseline)
`(since 6.4)` | QTRY_COMPARE_NE_WITH_TIMEOUT(computed, baseline, timeout)
| QTRY_COMPARE_WITH_TIMEOUT(actual, expected, timeout)
| QTRY_VERIFY2(condition, message)
| QTRY_VERIFY(condition)
| QTRY_VERIFY2_WITH_TIMEOUT(condition, message, timeout)
| QTRY_VERIFY_WITH_TIMEOUT(condition, timeout)
| QVERIFY2(condition, message)
| QVERIFY(condition)
`(since 6.3)` | QVERIFY_THROWS_EXCEPTION(exceptiontype, ...)
`(since 6.3)` | QVERIFY_THROWS_NO_EXCEPTION(...)

## Detailed Description

See the Qt Test Overview for information about how to write unit tests.

## Classes

### class QTouchEventSequence

The QTouchEventSequence class is used to simulate a sequence of touch events. More...

### class QTouchEventWidgetSequence

The QTouchEventWidgetSequence class is used to simulate a sequence of touch events for a widget. More...

### class ThrowOnFailDisabler

### class ThrowOnFailEnabler

### class ThrowOnSkipDisabler

### class ThrowOnSkipEnabler

## Type Documentation

### enum QTest::KeyAction

This enum describes possible actions for key handling.

Constant | Value | Description
--- | --- | ---
`QTest::Press` | `0` | The key is pressed.
`QTest::Release` | `1` | The key is released.
`QTest::Click` | `2` | The key is clicked (pressed and released).
`QTest::Shortcut` | `3` | A shortcut is activated. This value has been added in Qt 5.6.

### enum QTest::MouseAction

This enum describes possible actions for mouse handling.

Constant | Value | Description
--- | --- | ---
`QTest::MousePress` | `0` | A mouse button is pressed.
`QTest::MouseRelease` | `1` | A mouse button is released.
`QTest::MouseClick` | `2` | A mouse button is clicked (pressed and released).
`QTest::MouseDClick` | `3` | A mouse button is double clicked (pressed and released twice).
`QTest::MouseMove` | `4` | The mouse pointer has moved.

### enum QTest::QBenchmarkMetric

This enum lists all the things that can be benchmarked.

Constant | Value | Description
--- | --- | ---
`QTest::FramesPerSecond` | `0` | Frames per second
`QTest::BitsPerSecond` | `1` | Bits per second
`QTest::BytesPerSecond` | `2` | Bytes per second
`QTest::WalltimeMilliseconds` | `3` | Clock time in milliseconds
`QTest::WalltimeNanoseconds` | `7` | Clock time in nanoseconds
`QTest::BytesAllocated` | `8` | Memory usage in bytes
`QTest::Events` | `6` | Event count
`QTest::CPUTicks` | `4` | CPU time
`QTest::CPUMigrations` | `9` | Process migrations between CPUs
`QTest::CPUCycles` | `10` | CPU cycles
`QTest::RefCPUCycles` | `30` | Reference CPU cycles
`QTest::BusCycles` | `11` | Bus cycles
`QTest::StalledCycles` | `12` | Cycles stalled
`QTest::InstructionReads` | `5` | Instruction reads
`QTest::Instructions` | `13` | Instructions executed
`QTest::BranchInstructions` | `14` | Branch-type instructions
`QTest::BranchMisses` | `15` | Branch instructions that were mispredicted
`QTest::CacheReferences` | `16` | Cache accesses of any type
`QTest::CacheMisses` | `20` | Cache misses of any type
`QTest::CacheReads` | `17` | Cache reads / loads
`QTest::CacheReadMisses` | `21` | Cache read / load misses
`QTest::CacheWrites` | `18` | Cache writes / stores
`QTest::CacheWriteMisses` | `22` | Cache write / store misses
`QTest::CachePrefetches` | `19` | Cache prefetches
`QTest::CachePrefetchMisses` | `23` | Cache prefetch misses
`QTest::ContextSwitches` | `24` | Context switches
`QTest::PageFaults` | `25` | Page faults of any type
`QTest::MinorPageFaults` | `26` | Minor page faults
`QTest::MajorPageFaults` | `27` | Major page faults
`QTest::AlignmentFaults` | `28` | Faults caused due to misalignment
`QTest::EmulationFaults` | `29` | Faults that needed software emulation

Note that `WalltimeNanoseconds` and `BytesAllocated` are only provided for use via setBenchmarkResult(), and results in those metrics are not able to be provided automatically by the QTest framework.

See also QTest::benchmarkMetricName() and QTest::benchmarkMetricUnit().

### enum QTest::TestFailMode

This enum describes the modes for handling a check, such as by QVERIFY() or QCOMPARE() macros, that is known to fail. The mode applies regardless of whether the check fails or succeeds.

Constant | Value | Description
--- | --- | ---
`QTest::Abort` | `1` | Aborts the execution of the test. Use this mode when it doesn't make sense to execute the test any further after the problematic check.
`QTest::Continue` | `2` | Continues execution of the test after the problematic check.

See also QEXPECT_FAIL().

## Function Documentation

### template <typename T> void QTest::addColumn(const char *name, T *dummy = 0)

Adds a column with type `T` to the current test data. name is the name of the column. dummy is a workaround for buggy compilers and can be ignored.

To populate the column with values, newRow() can be used. Use QFETCH() to fetch the data in the actual test.

Example:

         QTest::addColumn<int>("intval");
         QTest::addColumn<QString>("str");
         QTest::addColumn<double>("dbl");
         QTest::newRow("row1") << 1 << "hello" << 1.5;

Note: This function can only be used called as part of a test's data function that is invoked by the test framework.

See Data Driven Testing for a more extensive example.

See also QTest::newRow(), QFETCH(), and QMetaType.

### QTestData &QTest::addRow(const char *format, ...)

Appends a new row to the current test data.

The function's arguments are passed to std::snprintf() for formatting according to format. See the std::snprintf() documentation for caveats and limitations.

The test output will identify the test run with this test data using the name that results from this formatting.

Returns a QTestData reference that can be used to stream in data, one value for each column in the table.

Example:

         QTest::addColumn<int>("input");
         QTest::addColumn<QString>("output");
         QTest::addRow("%d", 0) << 0 << QString("0");
         QTest::addRow("%d", 1) << 1 << QString("1");

Note: This function can only be called as part of a test's data function that is invoked by the test framework.

See Data Driven Testing for a more extensive example.

See also newRow(), addColumn(), and QFETCH().

### const char *QTest::benchmarkMetricName(QTest::QBenchmarkMetric metric)

Returns the enum value metric as a character string.

### const char *QTest::benchmarkMetricUnit(QTest::QBenchmarkMetric metric)

Returns the units of measure for the specified metric.

### QPointingDevice *QTest::createTouchDevice(QInputDevice::DeviceType devType = QInputDevice::DeviceType::TouchScreen, QInputDevice::Capabilities caps = QInputDevice::Capability::Position)

Creates a dummy touch device of type devType with capabilities caps for simulation of touch events.

The touch device will be registered with the Qt window system interface. You should typically use createTouchDevice() to initialize a QPointingDevice member variable in your test case class, use the same instance for all tests and delete it when no longer needed.

See also QTest::QTouchEventSequence and touchEvent().

### const char *QTest::currentAppName()

Returns the name of the binary that is currently executed.

### const char *QTest::currentDataTag()

Returns the name of the current test data. If the test doesn't have any assigned testdata, the function returns `nullptr`.

### bool QTest::currentTestFailed()

Returns `true` if the current test function has failed, otherwise false.

See also QTest::currentTestResolved().

### const char *QTest::currentTestFunction()

Returns the name of the test function that is currently executed.

Example:

     void MyTestClass::cleanup()
     {
         if (qstrcmp(QTest::currentTestFunction(), "myDatabaseTest") == 0) {
             // clean up all database connections
             closeAllDatabases();
         }
     }

### `[since 6.5]` bool QTest::currentTestResolved()

Returns `true` if the current test function has failed or skipped.

This applies if the test has failed or exercised a skip. When it is true, the test function should return early. In particular, the `QTRY_*` macros and the test event loop terminate their loops early if executed during the test function (but not its cleanup()). After a test has called a helper function that uses this module's macros, it can use this function to test whether to return early.

This function was introduced in Qt 6.5.

See also QTest::currentTestFailed().

### `[since 6.3]` void QTest::failOnWarning(const QRegularExpression &messagePattern)

Appends a test failure to the test log for each warning that matches messagePattern.

The test function will continue execution when a failure is added. To abort the test instead, you can check currentTestFailed() and return early if it's `true`.

For each warning, the first pattern that matches will cause a failure, and the remaining patterns will be ignored.

All patterns are cleared at the end of each test function.

     void FileTest::loadFiles()
     {
         QTest::failOnWarning(QRegularExpression("^Failed to load"));

         // Each of these will cause a test failure:
         qWarning() << "Failed to load image";
         qWarning() << "Failed to load video";
     }

To fail every test that triggers a given warning, pass a suitable regular expression to this function in init():

     void FileTest::init()
     {
         QTest::failOnWarning(
             QRegularExpression("QFile::.*: File(.*) already open"));
     }

For the common case of failing on any warning pass no parameter:

     void FileTest::init()
     {
         QTest::failOnWarning();
     }

Note: ignoreMessage() takes precedence over this function, so any warnings that match a pattern given to both `ignoreMessage()` and `failOnWarning()` will be ignored.

This function was introduced in Qt 6.3.

See also QTEST_FATAL_FAIL.

### `[since 6.8]` void QTest::failOnWarning()

Appends a test failure to the test log if any warning is output.

This function overloads QTest::failOnWarning().

This function was introduced in Qt 6.8.

See also failOnWarning(const char *).

### `[since 6.3]` void QTest::failOnWarning(const char *message)

Appends a test failure to the test log if the message is output.

This function overloads QTest::failOnWarning().

This function was introduced in Qt 6.3.

See also failOnWarning().

### void QTest::ignoreMessage(QtMsgType type, const char *message)

Ignores messages created by qDebug(), qInfo() or qWarning(). If the message with the corresponding type is outputted, it will be removed from the test log. If the test finished and the message was not outputted, a test failure is appended to the test log.

Note: Invoking this function will only ignore one message. If the message you want to ignore is output twice, you have to call ignoreMessage() twice, too.

Example:

     QDir dir;
     QTest::ignoreMessage(QtWarningMsg, "QDir::mkdir: Empty or null file name(s)");
     dir.mkdir("");

The example above tests that QDir::mkdir() outputs the right warning when invoked with an invalid file name.

Note: message will be interpreted as UTF-8.

### void QTest::ignoreMessage(QtMsgType type, const QRegularExpression &messagePattern)

Ignores messages created by qDebug(), qInfo() or qWarning(). If the message matching messagePattern with the corresponding type is outputted, it will be removed from the test log. If the test finished and the message was not outputted, a test failure is appended to the test log.

Note: Invoking this function will only ignore one message. If the message you want to ignore is output twice, you have to call ignoreMessage() twice, too.

This is an overloaded function.

### void QTest::keyClick(QWidget *widget, Qt::Key key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)

Simulates clicking of key with an optional modifier on a widget. If delay is larger than 0, the test will wait for delay milliseconds before clicking the key.

Examples:

     QTest::keyClick(myWidget, Qt::Key_Escape);

     QTest::keyClick(myWidget, Qt::Key_Escape, Qt::ShiftModifier, 200);

The first example above simulates clicking the `escape` key on `myWidget` without any keyboard modifiers and without delay. The second example simulates clicking `shift-escape` on `myWidget` following a 200 ms delay of the test.

See also QTest::keyClicks().

### void QTest::keyClick(QWidget *widget, char key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)

Simulates clicking of key with an optional modifier on a widget. If delay is larger than 0, the test will wait for delay milliseconds before clicking the key.

Example:

     QTest::keyClick(myWidget, 'a');

The example above simulates clicking `a` on `myWidget` without any keyboard modifiers and without delay of the test.

This is an overloaded function.

See also QTest::keyClicks().

### void QTest::keyClick(QWindow *window, Qt::Key key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)

Simulates clicking of key with an optional modifier on a window. If delay is larger than 0, the test will wait for delay milliseconds before clicking the key.

Examples:

     QTest::keyClick(&myWindow, Qt::Key_Escape);
     QTest::keyClick(&myWindow, Qt::Key_Escape, Qt::ShiftModifier, 200);

The first example above simulates clicking the `escape` key on `myWindow` without any keyboard modifiers and without delay. The second example simulates clicking `shift-escape` on `myWindow` following a 200 ms delay of the test.

This is an overloaded function.

See also QTest::keyClicks().

### void QTest::keyClick(QWindow *window, char key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)

Simulates clicking of key with an optional modifier on a window. If delay is larger than 0, the test will wait for delay milliseconds before clicking the key.

Example:

     QWidget myWindow;
     QTest::keyClick(&myWindow, Qt::Key_Tab);

The example above simulates clicking `a` on `myWindow` without any keyboard modifiers and without delay of the test.

This is an overloaded function.

See also QTest::keyClicks().

### void QTest::keyClicks(QWidget *widget, const QString &sequence, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)

Simulates clicking a sequence of keys on a widget. Optionally, a keyboard modifier can be specified as well as a delay (in milliseconds) of the test before each key click.

Example:

     QTest::keyClicks(myWidget, "hello world");

The example above simulates clicking the sequence of keys representing "hello world" on `myWidget` without any keyboard modifiers and without delay of the test.

See also QTest::keyClick().

### void QTest::keyEvent(QTest::KeyAction action, QWidget *widget, Qt::Key key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)

Sends a Qt key event to widget with the given key and an associated action. Optionally, a keyboard modifier can be specified, as well as a delay (in milliseconds) of the test before sending the event.

### void QTest::keyEvent(QTest::KeyAction action, QWidget *widget, char ascii, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)

Sends a Qt key event to widget with the given key ascii and an associated action. Optionally, a keyboard modifier can be specified, as well as a delay (in milliseconds) of the test before sending the event.

This is an overloaded function.

### void QTest::keyEvent(QTest::KeyAction action, QWindow *window, Qt::Key key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)

Sends a Qt key event to window with the given key and an associated action. Optionally, a keyboard modifier can be specified, as well as a delay (in milliseconds) of the test before sending the event.

This is an overloaded function.

### void QTest::keyEvent(QTest::KeyAction action, QWindow *window, char ascii, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)

Sends a Qt key event to window with the given key ascii and an associated action. Optionally, a keyboard modifier can be specified, as well as a delay (in milliseconds) of the test before sending the event.

This is an overloaded function.

### void QTest::keyPress(QWidget *widget, Qt::Key key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)

Simulates pressing a key with an optional modifier on a widget. If delay is larger than 0, the test will wait for delay milliseconds before pressing the key.

Note: At some point you should release the key using keyRelease().

See also QTest::keyRelease() and QTest::keyClick().

### void QTest::keyPress(QWidget *widget, char key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)

Simulates pressing a key with an optional modifier on a widget. If delay is larger than 0, the test will wait for delay milliseconds before pressing the key.

Note: At some point you should release the key using keyRelease().

This is an overloaded function.

See also QTest::keyRelease() and QTest::keyClick().

### void QTest::keyPress(QWindow *window, Qt::Key key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)

Simulates pressing a key with an optional modifier on a window. If delay is larger than 0, the test will wait for delay milliseconds before pressing the key.

Note: At some point you should release the key using keyRelease().

This is an overloaded function.

See also QTest::keyRelease() and QTest::keyClick().

### void QTest::keyPress(QWindow *window, char key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)

Simulates pressing a key with an optional modifier on a window. If delay is larger than 0, the test will wait for delay milliseconds before pressing the key.

Note: At some point you should release the key using keyRelease().

This is an overloaded function.

See also QTest::keyRelease() and QTest::keyClick().

### void QTest::keyRelease(QWidget *widget, Qt::Key key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)

Simulates releasing a key with an optional modifier on a widget. If delay is larger than 0, the test will wait for delay milliseconds before releasing the key.

See also QTest::keyPress() and QTest::keyClick().

### void QTest::keyRelease(QWidget *widget, char key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)

Simulates releasing a key with an optional modifier on a widget. If delay is larger than 0, the test will wait for delay milliseconds before releasing the key.

This is an overloaded function.

See also QTest::keyClick().

### void QTest::keyRelease(QWindow *window, Qt::Key key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)

Simulates releasing a key with an optional modifier on a window. If delay is larger than 0, the test will wait for delay milliseconds before releasing the key.

This is an overloaded function.

See also QTest::keyPress() and QTest::keyClick().

### void QTest::keyRelease(QWindow *window, char key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1)

Simulates releasing a key with an optional modifier on a window. If delay is larger than 0, the test will wait for delay milliseconds before releasing the key.

This is an overloaded function.

See also QTest::keyClick().

### void QTest::keySequence(QWidget *widget, const QKeySequence &keySequence)

Simulates typing of keySequence into a widget.

This is an overloaded function.

See also QTest::keyClick() and QTest::keyClicks().

### void QTest::keySequence(QWindow *window, const QKeySequence &keySequence)

Simulates typing of keySequence into a window.

This is an overloaded function.

See also QTest::keyClick() and QTest::keyClicks().

### void QTest::mouseClick(QWidget *widget, Qt::MouseButton button, Qt::KeyboardModifiers modifier = Qt::KeyboardModifiers(), QPoint pos = QPoint(), int delay = -1)

Simulates clicking a mouse button with an optional modifier on a widget. The position of the click is defined by pos; the default position is the center of the widget. If delay is specified, the test will wait for the specified amount of milliseconds before pressing and before releasing the button.

See also QTest::mousePress() and QTest::mouseRelease().

### void QTest::mouseClick(QWindow *window, Qt::MouseButton button, Qt::KeyboardModifiers stateKey = Qt::KeyboardModifiers(), QPoint pos = QPoint(), int delay = -1)

Simulates clicking a mouse button with an optional stateKey modifier on a window. The position of the click is defined by pos; the default position is the center of the window. If delay is specified, the test will wait for the specified amount of milliseconds before pressing and before releasing the button.

This is an overloaded function.

See also QTest::mousePress() and QTest::mouseRelease().

### void QTest::mouseDClick(QWidget *widget, Qt::MouseButton button, Qt::KeyboardModifiers modifier = Qt::KeyboardModifiers(), QPoint pos = QPoint(), int delay = -1)

Simulates double clicking a mouse button with an optional modifier on a widget. The position of the click is defined by pos; the default position is the center of the widget. If delay is specified, the test will wait for the specified amount of milliseconds before each press and release.

See also QTest::mouseClick().

### void QTest::mouseDClick(QWindow *window, Qt::MouseButton button, Qt::KeyboardModifiers stateKey = Qt::KeyboardModifiers(), QPoint pos = QPoint(), int delay = -1)

Simulates double clicking a mouse button with an optional stateKey modifier on a window. The position of the click is defined by pos; the default position is the center of the window. If delay is specified, the test will wait for the specified amount of milliseconds before each press and release.

This is an overloaded function.

See also QTest::mouseClick().

### void QTest::mouseMove(QWidget *widget, QPoint pos = QPoint(), int delay = -1)

Moves the mouse pointer to a widget. If pos is not specified, the mouse pointer moves to the center of the widget. If a delay (in milliseconds) is given, the test will wait before moving the mouse pointer.

### void QTest::mouseMove(QWindow *window, QPoint pos = QPoint(), int delay = -1)

Moves the mouse pointer to a window. If pos is not specified, the mouse pointer moves to the center of the window. If a delay (in milliseconds) is given, the test will wait before moving the mouse pointer.

This is an overloaded function.

### void QTest::mousePress(QWidget *widget, Qt::MouseButton button, Qt::KeyboardModifiers modifier = Qt::KeyboardModifiers(), QPoint pos = QPoint(), int delay = -1)

Simulates pressing a mouse button with an optional modifier on a widget. The position is defined by pos; the default position is the center of the widget. If delay is specified, the test will wait for the specified amount of milliseconds before the press.

See also QTest::mouseRelease() and QTest::mouseClick().

### void QTest::mousePress(QWindow *window, Qt::MouseButton button, Qt::KeyboardModifiers stateKey = Qt::KeyboardModifiers(), QPoint pos = QPoint(), int delay = -1)

Simulates pressing a mouse button with an optional stateKey modifier on a window. The position is defined by pos; the default position is the center of the window. If delay is specified, the test will wait for the specified amount of milliseconds before the press.

This is an overloaded function.

See also QTest::mouseRelease() and QTest::mouseClick().

### void QTest::mouseRelease(QWidget *widget, Qt::MouseButton button, Qt::KeyboardModifiers modifier = Qt::KeyboardModifiers(), QPoint pos = QPoint(), int delay = -1)

Simulates releasing a mouse button with an optional modifier on a widget. The position of the release is defined by pos; the default position is the center of the widget. If delay is specified, the test will wait for the specified amount of milliseconds before releasing the button; otherwise, it will wait for a default amount of time (1 ms), which can be overridden via command-line arguments.

Note: If you wish to test a double-click by sending events individually, specify a short delay, greater than the default, on both mouse release events. The total of the delays for the press, release, press and release must be less than QStyleHints::mouseDoubleClickInterval(). But if you don't need to check state between events, it's better to use QTest::mouseDClick().

     QSignalSpy doubleClickSpy(target, &TargetClass::doubleClicked);
     const QPoint p(1, 2);
     QTest::mousePress(&myWindow, Qt::LeftButton, Qt::NoModifier, p);
     QVERIFY(target.isPressed());
     QTest::mouseRelease(&myWindow, Qt::LeftButton, Qt::NoModifier, p, 10);
     QCOMPARE(target.isPressed(), false);
     QTest::mousePress(&myWindow, Qt::LeftButton, Qt::NoModifier, p, 10);
     QCOMPARE(target.pressCount(), 2);
     QTest::mouseRelease(&myWindow, Qt::LeftButton, Qt::NoModifier, p, 10);
     QCOMPARE(doubleClickSpy.count(), 1);

See also QTest::mousePress() and QTest::mouseClick().

### void QTest::mouseRelease(QWindow *window, Qt::MouseButton button, Qt::KeyboardModifiers stateKey = Qt::KeyboardModifiers(), QPoint pos = QPoint(), int delay = -1)

Simulates releasing a mouse button with an optional stateKey modifier on a window. The position of the release is defined by pos; the default position is the center of the window. If delay is specified, the test will wait for the specified amount of milliseconds before releasing the button; otherwise, it will wait for a default amount of time (1 ms), which can be overridden via command-line arguments.

Note: If you wish to test a double-click by sending events individually, specify a short delay, greater than the default, on both mouse release events. The total of the delays for the press, release, press and release must be less than QStyleHints::mouseDoubleClickInterval(). But if you don't need to check state between events, it's better to use QTest::mouseDClick().

     QSignalSpy doubleClickSpy(target, &TargetClass::doubleClicked);
     const QPoint p(1, 2);
     QTest::mousePress(&myWindow, Qt::LeftButton, Qt::NoModifier, p);
     QVERIFY(target.isPressed());
     QTest::mouseRelease(&myWindow, Qt::LeftButton, Qt::NoModifier, p, 10);
     QCOMPARE(target.isPressed(), false);
     QTest::mousePress(&myWindow, Qt::LeftButton, Qt::NoModifier, p, 10);
     QCOMPARE(target.pressCount(), 2);
     QTest::mouseRelease(&myWindow, Qt::LeftButton, Qt::NoModifier, p, 10);
     QCOMPARE(doubleClickSpy.count(), 1);

This is an overloaded function.

See also QTest::mousePress() and QTest::mouseClick().

### QTestData &QTest::newRow(const char *dataTag)

Appends a new row to the current test data.

The test output will identify the test run with this test data using the name dataTag.

Returns a QTestData reference that can be used to stream in data, one value for each column in the table.

Example:

     void MyTestClass::addSingleStringRows()
     {
         QTest::addColumn<QString>("aString");
         QTest::newRow("just.hello") << QString("hello");
         QTest::newRow("a.null.string") << QString();
     }

Note: This function can only be called as part of a test's data function that is invoked by the test framework.

See Data Driven Testing for a more extensive example.

See also addRow(), addColumn(), and QFETCH().

### int QTest::qExec(QObject *testObject, int argc = 0, char **argv = nullptr)

Executes tests declared in testObject. In addition, the private slots `initTestCase()`, `cleanupTestCase()`, `init()` and `cleanup()` are executed if they exist. See Creating a Test for more details.

Optionally, the command line arguments argc and argv can be provided. For a list of recognized arguments, read Qt Test Command Line Arguments.

The following example will run all tests in `MyTestObject`:

     MyTestObject test1;
     QTest::qExec(&test1);

This function returns 0 if no tests failed, or a value other than 0 if one or more tests failed or in case of unhandled exceptions. (Skipped tests do not influence the return value.)

For stand-alone test applications, the convenience macro QTEST_MAIN() can be used to declare a main() function that parses the command line arguments and executes the tests, avoiding the need to call this function explicitly.

The return value from this function is also the exit code of the test application when the QTEST_MAIN() macro is used.

For stand-alone test applications, this function should not be called more than once, as command-line options for logging test output to files and executing individual test functions will not behave correctly.

Note: This function is not reentrant, only one test can run at a time. A test that was executed with qExec() can't run another test via qExec() and threads are not allowed to call qExec() simultaneously.

If you have programmatically created the arguments, as opposed to getting them from the arguments in `main()`, it is likely of interest to use QTest::qExec(QObject *, const QStringList &) since it is Unicode safe.

See also QTEST_MAIN(), QTEST_GUILESS_MAIN(), and QTEST_APPLESS_MAIN().

### int QTest::qExec(QObject *testObject, const QStringList &arguments)

Behaves identically to qExec(QObject *, int, char**) but takes a QStringList of arguments instead of a `char**` list.

This is an overloaded function.

### QSharedPointer<QTemporaryDir> QTest::qExtractTestData(const QString &dirName)

Extracts a directory from resources to disk. The content is extracted recursively to a temporary folder. The extracted content is removed automatically once the last reference to the return value goes out of scope.

dirName is the name of the directory to extract from resources.

Returns the temporary directory where the data was extracted or null in case of errors.

### `[since 6.5]` void QTest::qRegisterTestCase(const QString &name, QTest::TestEntryFunction entryFunction)

Registers the test name, with entry function entryFunction, in a central test case registry for the current binary.

The name will be listed when running the batch test binary with no parameters. Running the test binary with the argv[1] of name will result in entryFunction being called.

This function was introduced in Qt 6.5.

### `[since 6.7]` void QTest::qSleep(std::chrono::milliseconds msecs)

Sleeps for msecs, blocking execution of the test.

This method will not do any event processing and will leave your test unresponsive. Network communication might time out while sleeping. Use QTest::qWait() to do non-blocking sleeping.

msecs must be greater than 0ms.

Note: Starting from Qt 6.7, this function is implemented using `std::this_thread::sleep_for`, so the accuracy of time spent depends on the Standard Library implementation. Before Qt 6.7 this function called either `nanosleep()` on Unix or `Sleep()` on Windows, so the accuracy of time spent in this function depended on the operating system.

Example:

     using namespace std::chrono_literals;
     QTest::qSleep(250ms);

This function was introduced in Qt 6.7.

See also QTest::qWait().

### void QTest::qSleep(int ms)

Sleeps for ms milliseconds, blocking execution of the test.

Equivalent to calling:

     QTest::qSleep(std::chrono::milliseconds{ms});

This is an overloaded function.

### `[since 6.7]` void QTest::qWait(std::chrono::milliseconds msecs)

Waits for msecs. While waiting, events will be processed and your test will stay responsive to user interface events or network communication.

Example:

         using namespace std::chrono_literals;
         int i = 0;
         while (myNetworkServerNotResponding() && i++ < 50)
             QTest::qWait(250ms);

The code above will wait until the network server is responding for a maximum of about 12.5 seconds.

The QTRY_* macros are usually a better choice than qWait(). qWait() always pauses for the full timeout, which can leave the test idle and slow down execution.

The `QTRY_*` macros poll the condition until it succeeds or the timeout expires. Your test therefore continues as soon as possible and stays more reliable. If the condition still fails, the macros double the timeout once and report the new value so that you can adjust it.

For example, rewrite the code above as:

     QTRY_VERIFY_WITH_TIMEOUT(!myNetworkServerNotResponding(), 12.5s);

This function was introduced in Qt 6.7.

See also QTest::qSleep(), QSignalSpy::wait(), and QTRY_VERIFY_WITH_TIMEOUT().

### void QTest::qWait(int msecs)

Waits for msecs. Equivalent to calling:

     QTest::qWait(std::chrono::milliseconds{msecs});

This is an overloaded function.

### `[since 6.7]` template <typename Functor> bool QTest::qWaitFor(Functor predicate, QDeadlineTimer deadline = QDeadlineTimer(Internal::defaultTryTimeout))

Waits until deadline has expired, or until predicate returns true, whichever happens first.

Returns `true` if predicate returned true at any point, otherwise returns `false`.

Example:

         MyObject obj;
         obj.startup();
         using namespace std::chrono_literals;
         const bool result = QTest::qWaitFor([&obj]() { return obj.isReady(); },
                                             QDeadlineTimer(3s));

The code above will wait for the object to become ready, for a maximum of three seconds.

This function was introduced in Qt 6.7.

### template <typename Functor> bool QTest::qWaitFor(Functor predicate, int timeout)

Waits for timeout milliseconds or until the predicate returns true.

This is equivalent to calling:

     qWaitFor(predicate, QDeadlineTimer(timeout));

This is an overloaded function.

### `[since 6.10]` bool QTest::qWaitForWindowActive(QWidget *widget, QDeadlineTimer timeout)

Returns `true` if widget is active within timeout milliseconds. Otherwise returns `false`.

The method is useful in tests that call QWidget::show() and rely on the widget actually being active (i.e. being visible and having focus) before proceeding.

Note: The method will time out and return `false` if another window prevents widget from becoming active.

Note: Since focus is an exclusive property, widget may loose its focus to another window at any time - even after the method has returned `true`.

This function was introduced in Qt 6.10.

See also qWaitForWindowExposed() and QWidget::isActiveWindow().

### `[since 6.10]` bool QTest::qWaitForWindowActive(QWindow *window, QDeadlineTimer timeout)

Returns `true`, if window is active within timeout. Otherwise returns `false`.

The method is useful in tests that call QWindow::show() and rely on the window actually being active (i.e. being visible and having focus) before proceeding.

Note: The method will time out and return `false` if another window prevents window from becoming active.

Note: Since focus is an exclusive property, window may loose its focus to another window at any time - even after the method has returned `true`.

This function was introduced in Qt 6.10.

See also qWaitForWindowExposed(), qWaitForWindowFocused(), and QWindow::isActive().

### `[since 6.10]` bool QTest::qWaitForWindowActive(QWidget *widget)

This function uses the default timeout of 5 seconds.

This is an overloaded function.

This function was introduced in Qt 6.10.

### `[since 6.10]` bool QTest::qWaitForWindowActive(QWindow *window)

This function uses the default timeout of 5 seconds.

This is an overloaded function.

This function was introduced in Qt 6.10.

### bool QTest::qWaitForWindowActive(QWidget *widget, int timeout)

The timeout is in milliseconds.

This is an overloaded function.

### bool QTest::qWaitForWindowActive(QWindow *window, int timeout)

The timeout is in milliseconds.

This is an overloaded function.

### `[since 6.10]` bool QTest::qWaitForWindowExposed(QWidget *widget, QDeadlineTimer timeout)

Returns `true` if widget is exposed within timeout milliseconds. Otherwise returns `false`.

The method is useful in tests that call QWidget::show() and rely on the widget actually being being visible before proceeding.

Note: A window mapped to screen may still not be considered exposed, if the window client area is not visible, e.g. because it is completely covered by other windows. In such cases, the method will time out and return `false`.

This function was introduced in Qt 6.10.

See also qWaitForWindowActive(), QWidget::isVisible(), and QWindow::isExposed().

### `[since 6.10]` bool QTest::qWaitForWindowExposed(QWindow *window, QDeadlineTimer timeout)

Returns `true`, if window is exposed within timeout. Otherwise returns `false`.

The method is useful in tests that call QWindow::show() and rely on the window actually being being visible before proceeding.

Note: A window mapped to screen may still not be considered exposed, if the window client area is not visible, e.g. because it is completely covered by other windows. In such cases, the method will time out and return `false`.

This function was introduced in Qt 6.10.

See also qWaitForWindowActive() and QWindow::isExposed().

### `[since 6.10]` bool QTest::qWaitForWindowExposed(QWidget *widget)

This function uses the default timeout of 5 seconds.

This is an overloaded function.

This function was introduced in Qt 6.10.

### `[since 6.10]` bool QTest::qWaitForWindowExposed(QWindow *window)

This function uses the default timeout of 5 seconds.

This is an overloaded function.

This function was introduced in Qt 6.10.

### bool QTest::qWaitForWindowExposed(QWidget *widget, int timeout)

The timeout is in milliseconds.

This is an overloaded function.

### bool QTest::qWaitForWindowExposed(QWindow *window, int timeout)

The timeout is in milliseconds.

This is an overloaded function.

### `[since 6.7]` bool QTest::qWaitForWindowFocused(QWidget *widget, QDeadlineTimer timeout)

Returns `true`, if widget is the focus window within timeout. Otherwise returns `false`.

The method is useful in tests that call QWidget::show() and rely on the widget having focus (for receiving keyboard events e.g.) before proceeding.

Note: The method will time out and return `false` if another window prevents widget from becoming focused.

Note: Since focus is an exclusive property, widget may loose its focus to another window at any time - even after the method has returned `true`.

This function was introduced in Qt 6.7.

See also qWaitForWindowExposed(), qWaitForWindowActive(), and QGuiApplication::focusWindow().

### `[since 6.7]` bool QTest::qWaitForWindowFocused(QWindow *window, QDeadlineTimer timeout)

Returns `true`, if window is the focus window within timeout. Otherwise returns `false`.

The method is useful in tests that call QWindow::show() and rely on the window having focus (for receiving keyboard events e.g.) before proceeding.

Note: The method will time out and return `false` if another window prevents window from becoming focused.

Note: Since focus is an exclusive property, window may loose its focus to another window at any time - even after the method has returned `true`.

This function was introduced in Qt 6.7.

See also qWaitForWindowExposed(), qWaitForWindowActive(), and QGuiApplication::focusWindow().

### `[since 6.10]` bool QTest::qWaitForWindowFocused(QWidget *widget)

This function uses the default timeout of 5 seconds.

This is an overloaded function.

This function was introduced in Qt 6.10.

### `[since 6.10]` bool QTest::qWaitForWindowFocused(QWindow *window)

This function uses the default timeout of 5 seconds.

This is an overloaded function.

This function was introduced in Qt 6.10.

### void QTest::setBenchmarkResult(qreal result, QTest::QBenchmarkMetric metric)

Sets the benchmark result for this test function to result.

Use this function if you want to report benchmark results without using the QBENCHMARK macro. Use metric to specify how Qt Test should interpret the results.

The context for the result will be the test function name and any data tag from the _data function. This function can only be called once in each test function, subsequent calls will replace the earlier reported results.

Note that the -iterations command line argument has no effect on test functions without the QBENCHMARK macro.

### `[noexcept, since 6.8]` void QTest::setThrowOnFail(bool enable)

Enables (enable = `true`) or disables ( enable = `false`) throwing on QCOMPARE()/QVERIFY() failures (as opposed to just returning from the immediately-surrounding function context).

The feature is reference-counted: If you call this function N times with `true`, you need to call it N times with `false` to get back to where you started.

This call has no effect when the QTEST_THROW_ON_FAIL C++ macro is defined.

Note: You must compile your tests with exceptions enabled to use this feature.

This function was introduced in Qt 6.8.

See also setThrowOnSkip(), ThrowOnFailEnabler, ThrowOnFailDisabler, and QTEST_THROW_ON_FAIL.

### `[noexcept, since 6.8]` void QTest::setThrowOnSkip(bool enable)

Enables (enable = `true`) or disables ( enable = `false`) throwing on QSKIP() (as opposed to just returning from the immediately-surrounding function context).

The feature is reference-counted: If you call this function N times with `true`, you need to call it N times with `false` to get back to where you started.

This call has no effect when the QTEST_THROW_ON_SKIP C++ macro is defined.

Note: You must compile your tests with exceptions enabled to use this feature.

This function was introduced in Qt 6.8.

See also setThrowOnFail(), ThrowOnSkipEnabler, ThrowOnSkipDisabler, and QTEST_THROW_ON_SKIP.

### char *QTest::toHexRepresentation(const char *ba, qsizetype length)

Returns a pointer to a string that is the string ba represented as a space-separated sequence of hex characters. If the input is considered too long, it is truncated. A trucation is indicated in the returned string as an ellipsis at the end. The caller has ownership of the returned pointer and must ensure it is later passed to operator delete[].

length is the length of the string ba.

### char *toString(QSizePolicy sp)

Returns a textual representation of size policy sp.

This is an overloaded function.

### template <typename T> char *QTest::toString(const T &value)

Returns a textual representation of value. This function is used by QCOMPARE() to output verbose information in case of a test failure.

You can add specializations or overloads of this function to your test to enable verbose output.

Note: Starting with Qt 5.5, you should prefer to provide a toString() function in the type's namespace instead of specializing this template. If your code needs to continue to work with the QTestLib from Qt 5.4 or earlier, you need to continue to use specialization.

Note: The caller of toString() must delete the returned data using `delete[]`. Your implementation should return a string created with `new[]` or qstrdup(). The easiest way to do so is to create a QByteArray or QString and call QTest::toString() on it (see second example below).

Example for specializing (Qt ≤ 5.4):

     namespace QTest {
         template<>
         char *toString(const MyPoint &point)
         {
             const QByteArray ba("MyPoint("
                                 + QByteArray::number(point.x()) + ", "
                                 + QByteArray::number(point.y()) + ')');
             return qstrdup(ba.data());
         }
     }

The example above defines a toString() specialization for a class called `MyPoint`. Whenever a comparison of two instances of `MyPoint` fails, QCOMPARE() will call this function to output the contents of `MyPoint` to the test log.

Same example, but with overloading (Qt ≥ 5.5):

     namespace {
         char *toString(const MyPoint &point)
         {
             return QTest::toString("MyPoint(" +
                                    QByteArray::number(point.x()) + ", " +
                                    QByteArray::number(point.y()) + ')');
         }
     }

See also QCOMPARE().

### char *toString(QSizePolicy::ControlType ct)

Returns a textual representation of control type ct.

This is an overloaded function.

### char *toString(QSizePolicy::ControlTypes cts)

Returns a textual representation of control types cts.

This is an overloaded function.

### char *toString(QSizePolicy::Policy p)

Returns a textual representation of policy p.

This is an overloaded function.

### char *QTest::toString(const QByteArray &ba)

Returns a textual representation of the byte array ba.

This is an overloaded function.

See also QTest::toHexRepresentation().

### char *QTest::toString(const QCborError &c)

Returns a textual representation of the given CBOR error c.

This is an overloaded function.

### char *QTest::toString(const QChar &character)

Returns a textual representation of the given character.

This is an overloaded function.

### char *QTest::toString(const QDate &date)

Returns a textual representation of the given date.

This is an overloaded function.

### char *QTest::toString(const QDateTime &dateTime)

Returns a textual representation of the date and time specified by dateTime.

This is an overloaded function.

### `[since 6.5]` char *QTest::toString(const QKeySequence &ks)

Returns a textual representation of the key sequence ks.

This is an overloaded function.

This function was introduced in Qt 6.5.

### char *QTest::toString(const QLatin1StringView &string)

Returns a textual representation of the given string.

This is an overloaded function.

### char *QTest::toString(const QPoint &point)

Returns a textual representation of the given point.

This is an overloaded function.

### char *QTest::toString(const QPointF &point)

Returns a textual representation of the given point.

This is an overloaded function.

### char *QTest::toString(const QRect &rectangle)

Returns a textual representation of the given rectangle.

This is an overloaded function.

### char *QTest::toString(const QRectF &rectangle)

Returns a textual representation of the given rectangle.

This is an overloaded function.

### char *QTest::toString(const QSize &size)

Returns a textual representation of the given size.

This is an overloaded function.

### char *QTest::toString(const QSizeF &size)

Returns a textual representation of the given size.

This is an overloaded function.

### char *QTest::toString(const QString &string)

Returns a textual representation of the given string.

This is an overloaded function.

### char *QTest::toString(const QStringView &string)

Returns a textual representation of the given string.

This is an overloaded function.

### char *QTest::toString(const QTime &time)

Returns a textual representation of the given time.

This is an overloaded function.

### char *QTest::toString(const QUrl &url)

Returns a textual representation of the given url.

This is an overloaded function.

### char *QTest::toString(const QUuid &uuid)

Returns a textual representation of the given uuid.

This is an overloaded function.

### char *QTest::toString(const QVariant &variant)

Returns a textual representation of the given variant.

This is an overloaded function.

### char *QTest::toString(const QVector2D &v)

Returns a textual representation of the 2D vector v.

This is an overloaded function.

### char *QTest::toString(const QVector3D &v)

Returns a textual representation of the 3D vector v.

This is an overloaded function.

### char *QTest::toString(const QVector4D &v)

Returns a textual representation of the 4D vector v.

This is an overloaded function.

### template <typename T1, typename T2> char *QTest::toString(const std::pair<T1, T2> &pair)

Returns a textual representation of the pair.

This is an overloaded function.

### template <typename... Types> char *QTest::toString(const std::tuple<Types...> &tuple)

Returns a textual representation of the given tuple.

This is an overloaded function.

### char *QTest::toString(std::nullptr_t)

Returns a string containing `nullptr`.

This is an overloaded function.

### QTest::QTouchEventWidgetSequence QTest::touchEvent(QWidget *widget, QPointingDevice *device, bool autoCommit = true)

Creates and returns a QTouchEventSequence for the device to simulate events for widget.

When adding touch events to the sequence, widget will also be used to translate the position provided to screen coordinates, unless another widget is provided in the respective calls to press(), move() etc.

The touch events are committed to the event system when the destructor of the QTouchEventSequence is called (ie when the object returned runs out of scope), unless autoCommit is set to false. When autoCommit is false, commit() has to be called manually.

createTouchDevice() can be called to create a test touch device for use with this function.

### QTest::QTouchEventSequence QTest::touchEvent(QWindow *window, QPointingDevice *device, bool autoCommit = true)

Creates and returns a QTouchEventSequence for the device to simulate events for window.

When adding touch events to the sequence, window will also be used to translate the position provided to screen coordinates, unless another window is provided in the respective calls to press(), move() etc.

The touch events are committed to the event system when the destructor of the QTouchEventSequence is called (ie when the object returned runs out of scope), unless autoCommit is set to false. When autoCommit is false, commit() has to be called manually.

createTouchDevice() can be called to create a test touch device for use with this function.

### `[since 6.8]` void QTest::wheelEvent(QWindow *window, QPointF pos, QPoint angleDelta, QPoint pixelDelta = QPoint(0, 0), Qt::KeyboardModifiers stateKey = Qt::NoModifier, Qt::ScrollPhase phase = Qt::NoScrollPhase)

Simulates a wheel event within window at position pos in local window coordinates. angleDelta contains the wheel rotation angle. A positive value means forward rotation, and a negative one means backward. pixelDelta contains the scrolling distance in pixels on screen. This value can be null. The keyboard states at the time of the event are specified by stateKey. The scrolling phase of the event is specified by phase.

This function was introduced in Qt 6.8.

## Macro Documentation

### QBENCHMARK

This macro is used to measure the performance of code within a test. The code to be benchmarked is contained within a code block following this macro.

For example:

     void TestBenchmark::simple()
     {
         QString str1 = u"This is a test string"_s;
         QString str2 = u"This is a test string"_s;
         QCOMPARE(str1.localeAwareCompare(str2), 0);
         QBENCHMARK {
             str1.localeAwareCompare(str2);
         }
     }

See also Creating a Benchmark and Writing a Benchmark.

### QBENCHMARK_ONCE

The QBENCHMARK_ONCE macro is for measuring performance of a code block by running it once.

This macro is used to measure the performance of code within a test. The code to be benchmarked is contained within a code block following this macro.

Unlike QBENCHMARK, the contents of the contained code block is only run once. The elapsed time will be reported as "0" if it's too short to be measured by the selected backend.

See also Creating a Benchmark and Writing a Benchmark.

### QCOMPARE(actual, expected)

The QCOMPARE() macro compares an actual value to an expected value using the equality operator. If actual and expected match, execution continues. If not, a failure is recorded in the test log and the test function returns without attempting any later checks.

Always respect QCOMPARE() parameter semantics. The first parameter passed to it should always be the actual value produced by the code-under-test, while the second parameter should always be the expected value. When the values don't match, QCOMPARE() prints them with the labels Actual and Expected. If the parameter order is swapped, debugging a failing test can be confusing and tests expecting zero may fail due to rounding errors.

QCOMPARE() tries to output the contents of the values if the comparison fails, so it is visible from the test log why the comparison failed.

Example:

     QCOMPARE(QString("hello").toUpper(), QString("HELLO"));

When comparing floating-point types (`float`, `double`, and `qfloat16`), qFuzzyCompare() is used for finite values. If qFuzzyIsNull() is true for both values, they are also considered equal. Infinities match if they have the same sign, and any NaN as actual value matches with any NaN as expected value (even though NaN != NaN, even when they're identical).

When comparing QList, arrays and initializer lists of the value type can be passed as expected value:

         const int expected[] = {8, 10, 12, 16, 20, 24};
         QCOMPARE(QFontDatabase::standardSizes(), expected);

Note that using initializer lists requires defining a helper macro to prevent the preprocessor from interpreting the commas as macro argument delimiters:

      #define ARG(...) __VA_ARGS__
          QCOMPARE(QFontDatabase::standardSizes(), ARG({8, 10, 12, 16, 20, 24}));
      #undef ARG

Note: This macro can only be used in a test function that is invoked by the test framework.

For your own classes, you can overload QTest::toString() to format values for output into the test log.

Example:

     char *toString(const MyType &t)
     {
         char *repr = new char[t.reprSize()];
         t.writeRepr(repr);
         return repr;
     }

The return from `toString()` must be a `new char []`. That is, it shall be released with `delete[]` (rather than `free()` or plain `delete`) once the calling code is done with it.

See also QVERIFY(), QTRY_COMPARE(), QTest::toString(), QEXPECT_FAIL(), QCOMPARE_EQ(), QCOMPARE_NE(), QCOMPARE_LT(), QCOMPARE_LE(), QCOMPARE_GT(), and QCOMPARE_GE().

### `[since 6.9]` QCOMPARE_3WAY(lhs, rhs, order)

The QCOMPARE_3WAY() macro applies the three-way comparison operator `<=>` to the input expressions lhs and rhs, and checks if the result is order. If that is true, execution continues. If not, a failure is recorded in the test log and the test function returns without attempting any later checks. The macro only accepts Qt:: and std:: ordering types as order argument, otherwise it asserts.

Note: order can be a Qt:: ordering type even if a `decltype(lhs <=> rhs)` is a std one. The result of `decltype(lhs <=> rhs)` operation should have the same strength as order. Otherwise, applying the macro will result in a compilation error. For example, if the result of `decltype(lhs <=> rhs)` has a weak ordering type, the order argument can't have partial or strong ordering types.

Note: The macro only works if the compiler supports the `<=>` operator, and otherwise it statically asserts that the prerequisite feature isn't available. Before a macro usage always check if `__cpp_lib_three_way_comparison` is defined, and use QSKIP, if it isn't.

Note: This macro can only be used in a test function that is invoked by the test framework.

For your own classes, you can overload QTest::toString() to format values for output into the test log.

This macro was introduced in Qt 6.9.

### `[since 6.4]` QCOMPARE_EQ(computed, baseline)

The QCOMPARE_EQ() macro checks that computed is equal to baseline using the equality operator. If that is true, execution continues. If not, a failure is recorded in the test log and the test function returns without attempting any later checks.

It is generally similar to calling `QVERIFY(computed == baseline);` but prints a formatted error message reporting computed and baseline argument expressions and values in case of failure.

Note: This macro can only be used in a test function that is invoked by the test framework.

For your own classes, you can overload QTest::toString() to format values for output into the test log.

Note: Unlike QCOMPARE(), this macro does not provide overloads for custom types and pointers. So passing e.g. two `const char *` values as parameters will compare pointers, while QCOMPARE() does a comparison of C-style strings.

This macro was introduced in Qt 6.4.

See also QCOMPARE(), QCOMPARE_NE(), QCOMPARE_LT(), QCOMPARE_LE(), QCOMPARE_GT(), and QCOMPARE_GE().

### `[since 6.4]` QCOMPARE_GE(computed, baseline)

The QCOMPARE_GE() macro checks that computed is at least baseline using the greater-than-or-equal-to operator. If that is true, execution continues. If not, a failure is recorded in the test log and the test function returns without attempting any later checks.

It is generally similar to calling `QVERIFY(computed >= baseline);` but prints a formatted error message reporting computed and baseline argument expressions and values in case of failure.

Note: This macro can only be used in a test function that is invoked by the test framework.

For your own classes, you can overload QTest::toString() to format values for output into the test log.

This macro was introduced in Qt 6.4.

See also QCOMPARE_EQ(), QCOMPARE_NE(), QCOMPARE_LT(), QCOMPARE_LE(), and QCOMPARE_GT().

### `[since 6.4]` QCOMPARE_GT(computed, baseline)

The QCOMPARE_GT() macro checks that computed is greater than baseline using the greater-than operator. If that is true, execution continues. If not, a failure is recorded in the test log and the test function returns without attempting any later checks.

It is generally similar to calling `QVERIFY(computed > baseline);` but prints a formatted error message reporting computed and baseline argument expressions and values in case of failure.

Note: This macro can only be used in a test function that is invoked by the test framework.

For your own classes, you can overload QTest::toString() to format values for output into the test log.

This macro was introduced in Qt 6.4.

See also QCOMPARE_EQ(), QCOMPARE_NE(), QCOMPARE_LT(), QCOMPARE_LE(), and QCOMPARE_GE().

### `[since 6.4]` QCOMPARE_LE(computed, baseline)

The QCOMPARE_LE() macro checks that computed is at most baseline using the less-than-or-equal-to operator. If that is true, execution continues. If not, a failure is recorded in the test log and the test function returns without attempting any later checks.

It is generally similar to calling `QVERIFY(computed <= baseline);` but prints a formatted error message reporting computed and baseline argument expressions and values in case of failure.

Note: This macro can only be used in a test function that is invoked by the test framework.

For your own classes, you can overload QTest::toString() to format values for output into the test log.

This macro was introduced in Qt 6.4.

See also QCOMPARE_EQ(), QCOMPARE_NE(), QCOMPARE_LT(), QCOMPARE_GT(), and QCOMPARE_GE().

### `[since 6.4]` QCOMPARE_LT(computed, baseline)

The QCOMPARE_LT() macro checks that computed is less than baseline using the less-than operator. If that is true, execution continues. If not, a failure is recorded in the test log and the test function returns without attempting any later checks.

It is generally similar to calling `QVERIFY(computed < baseline);` but prints a formatted error message reporting computed and baseline argument expressions and values in case of failure.

Note: This macro can only be used in a test function that is invoked by the test framework.

For your own classes, you can overload QTest::toString() to format values for output into the test log.

This macro was introduced in Qt 6.4.

See also QCOMPARE_EQ(), QCOMPARE_NE(), QCOMPARE_LE(), QCOMPARE_GT(), and QCOMPARE_GE().

### `[since 6.4]` QCOMPARE_NE(computed, baseline)

The QCOMPARE_NE() macro checks that computed is not equal to baseline using the inequality operator. If that is true, execution continues. If not, a failure is recorded in the test log and the test function returns without attempting any later checks.

It is generally similar to calling `QVERIFY(computed != baseline);` but prints a formatted error message reporting computed and baseline argument expressions and values in case of failure.

Note: This macro can only be used in a test function that is invoked by the test framework.

For your own classes, you can overload QTest::toString() to format values for output into the test log.

This macro was introduced in Qt 6.4.

See also QCOMPARE_EQ(), QCOMPARE_LT(), QCOMPARE_LE(), QCOMPARE_GT(), and QCOMPARE_GE().

### QEXPECT_FAIL(dataIndex, comment, mode)

The QEXPECT_FAIL() macro marks the next QCOMPARE() or QVERIFY() as an expected failure. Instead of adding a failure to the test log, an expected failure will be reported.

If a QVERIFY() or QCOMPARE() is marked as an expected failure, but passes instead, an unexpected pass (XPASS) is written to the test log and will be counted as a test failure.

The parameter dataIndex describes for which entry in the test data the failure is expected. Pass an empty string (`""`) if the failure is expected for all entries or if no test data exists.

comment will be appended to the test log for the expected failure.

mode is a QTest::TestFailMode and sets whether the test should continue to execute or not. The mode is applied regardless of whether the expected test failure occurs.

Note: This macro can only be used in a test function that is invoked by the test framework.

Example 1:

     QEXPECT_FAIL("", "Will fix in the next release", Continue);
     QCOMPARE(i, 42);
     QCOMPARE(j, 43);

In the example above, an expected fail will be written into the test output if the variable `i` is not 42. If the variable `i` is 42, an unexpected pass is written instead. The QEXPECT_FAIL() has no influence on the second QCOMPARE() statement in the example.

Example 2:

     QEXPECT_FAIL("data27", "Oh my, this is soooo broken", Abort);
     QCOMPARE(i, 42);

The above testfunction will not continue executing for the test data entry `data27` (regardless of the value of `i`).

See also QTest::TestFailMode, QVERIFY(), and QCOMPARE().

### QFAIL(message)

This macro can be used to force a test failure. The test stops executing and the failure message is appended to the test log.

Note: This macro can only be used in a test function that is invoked by the test framework.

Example:

     if (sizeof(int) != 4)
         QFAIL("This test has not been ported to this platform yet.");

### QFETCH(type, name)

The fetch macro creates a local variable named name with the type type on the stack. The name and type must match a column from the test's data table. This is asserted and the test will abort if the assertion fails.

Assuming a test has the following data:

     void TestQString::toInt_data()
     {
         QTest::addColumn<QString>("aString");
         QTest::addColumn<int>("expected");

         QTest::newRow("positive+value") << "42" << 42;
         QTest::newRow("negative-value") << "-42" << -42;
         QTest::newRow("zero") << "0" << 0;
     }

The test data has two elements, a QString called `aString` and an integer called `expected`. To fetch these values in the actual test:

     void TestQString::toInt()
     {
          QFETCH(QString, aString);
          QFETCH(int, expected);

          QCOMPARE(aString.toInt(), expected);
     }

`aString` and `expected` are variables on the stack that are initialized with the current test data.

Note: This macro can only be used in a test function that is invoked by the test framework. The test function must have a _data function.

### QFETCH_GLOBAL(type, name)

This macro fetches a variable named name with the type type from a row in the global data table. The name and type must match a column in the global data table. This is asserted and the test will abort if the assertion fails.

Assuming a test has the following data:

     void TestQLocale::initTestCase_data()
     {
         QTest::addColumn<QLocale>("locale");
         QTest::newRow("C") << QLocale::c();
         QTest::newRow("UKish") << QLocale("en_GB");
         QTest::newRow("USAish") << QLocale(QLocale::English, QLocale::UnitedStates);
     }

     void TestQLocale::roundTripInt_data()
     {
         QTest::addColumn<int>("number");
         QTest::newRow("zero") << 0;
         QTest::newRow("one") << 1;
         QTest::newRow("two") << 2;
         QTest::newRow("ten") << 10;
     }

The test's own data is a single number per row. In this case, `initTestCase_data()` also supplies a locale per row. Therefore, this test will be run with every combination of locale from the latter and number from the former. Thus, with four rows in the global table and three in the local, the test function is run for 12 distinct test-cases (4 * 3 = 12).

     void TestQLocale::roundTripInt()
     {
         QFETCH_GLOBAL(QLocale, locale);
         QFETCH(int, number);
         bool ok;
         QCOMPARE(locale.toInt(locale.toString(number), &ok), number);
         QVERIFY(ok);
     }

The locale is read from the global data table using QFETCH_GLOBAL(), and the number is read from the local data table using QFETCH().

Note: This macro can only be used in test methods of a class with an `initTestCase_data()` method.

### QFINDTESTDATA(filename)

Returns a QString for the testdata file referred to by filename, or an empty QString if the testdata file could not be found.

This macro allows the test to load data from an external file without hardcoding an absolute filename into the test, or using relative paths which may be error prone.

The returned path will be the first path from the following list which resolves to an existing file or directory:

- filename relative to QCoreApplication::applicationDirPath() (only if a QCoreApplication or QApplication object has been created).
- filename relative to the test's standard install directory (QLibraryInfo::TestsPath with the lowercased testcase name appended).
- filename relative to the directory containing the source file from which QFINDTESTDATA is invoked.

If the named file/directory does not exist at any of these locations, a warning is printed to the test log.

For example, in this code:

     bool tst_MyXmlParser::parse()
     {
         MyXmlParser parser;
         QString input = QFINDTESTDATA("testxml/simple1.xml");
         QVERIFY(parser.parse(input));
     }

The testdata file will be resolved as the first existing file from:

- `/home/user/build/myxmlparser/tests/tst_myxmlparser/testxml/simple1.xml`
- `/usr/local/Qt-5.0.0/tests/tst_myxmlparser/testxml/simple1.xml`
- `/home/user/sources/myxmlparser/tests/tst_myxmlparser/testxml/simple1.xml`

This allows the test to find its testdata regardless of whether the test has been installed, and regardless of whether the test's build tree is equal to the test's source tree.

Note: reliable detection of testdata from the source directory requires either that qmake is used, or the `QT_TESTCASE_BUILDDIR` macro is defined to point to the working directory from which the compiler is invoked, or only absolute paths to the source files are passed to the compiler. Otherwise, the absolute path of the source directory cannot be determined.

Note: The `QT_TESTCASE_BUILDDIR` macro is also implicitly defined if CMake is used and the QtTest module is linked to the target. You can change the default `QT_TESTCASE_BUILDDIR` by setting the QT_TESTCASE_BUILDDIR property on the target.

Note: For tests that use the QTEST_APPLESS_MAIN() macro to generate a `main()` function, `QFINDTESTDATA` will not attempt to find test data relative to QCoreApplication::applicationDirPath(). In practice, this means that tests using `QTEST_APPLESS_MAIN()` will fail to find their test data if run from a shadow build tree.

### QSKIP(description)

If called from a test function, the QSKIP() macro stops execution of the test without adding a failure to the test log. You can use it to skip tests that wouldn't make sense in the current configuration. For example, a test of font rendering may call QSKIP() if the needed fonts are not installed on the test system.

The text description is appended to the test log and should contain an explanation of why the test couldn't be executed.

If the test is data-driven, each call to QSKIP() in the test function will skip only the current row of test data, so an unconditional call to QSKIP() will produce one skip message in the test log for each row of test data.

If called from an `_data` function, the QSKIP() macro will stop execution of the `_data` function and will prevent execution of the associated test function. This entirely omits a data-driven test. To omit individual rows, make them conditional by using a simple `if (condition) newRow(...) << ...` in the `_data` function, instead of using QSKIP() in the test function.

If called from `initTestCase_data()`, the QSKIP() macro will skip all test and `_data` functions. If called from `initTestCase()` when there is no `initTestCase_data()`, or when it only sets up one row, QSKIP() will likewise skip the whole test. However, if `initTestCase_data()` contains more than one row, then `initTestCase()` is called (followed by each test and finally the wrap-up) once per row of it. Therefore, a call to QSKIP() in `initTestCase()` will merely skip all test functions for the current row of global data, set up by `initTestCase_data()`.

Note: This macro can only be used in a test function or `_data` function that is invoked by the test framework.

Example:

     if (!QSqlDatabase::drivers().contains("SQLITE"))
         QSKIP("This test requires the SQLITE database driver");

##### Skipping Known Bugs

If a test exposes a known bug that will not be fixed immediately, use the QEXPECT_FAIL() macro to document the failure and reference the bug tracking identifier for the known issue. When the test is run, expected failures will be marked as XFAIL in the test output and will not be counted as failures when setting the test program's return code. If an expected failure does not occur, the XPASS (unexpected pass) will be reported in the test output and will be counted as a test failure.

For known bugs, QEXPECT_FAIL() is better than QSKIP() because a developer cannot fix the bug without an XPASS result reminding them that the test needs to be updated too. If QSKIP() is used, there is no reminder to revise or re-enable the test, without which subsequent regressions will not be reported.

See also QEXPECT_FAIL() and Select Appropriate Mechanisms to Exclude Tests.

### QTEST(actual, testElement)

QTEST() is a convenience macro for QCOMPARE() that compares the value actual with the element testElement from the test's data. If there is no such element, the test asserts.

Apart from that, QTEST() behaves exactly as QCOMPARE().

Instead of writing:

     QFETCH(QString, myString);
     QCOMPARE(QString("hello").toUpper(), myString);

you can write:

     QTEST(QString("hello").toUpper(), "myString");

See also QCOMPARE().

### QTEST_APPLESS_MAIN(TestClass)

Implements a main() function that executes all tests in TestClass.

Behaves like QTEST_MAIN(), but doesn't instantiate a QApplication object. Use this macro for really simple stand-alone non-GUI tests.

See also QTEST_MAIN().

### QTEST_GUILESS_MAIN(TestClass)

Implements a main() function that instantiates a QCoreApplication object and the TestClass, and executes all tests in the order they were defined. Use this macro to build stand-alone executables.

Behaves like QTEST_MAIN(), but instantiates a QCoreApplication instead of the QApplication object. Use this macro if your test case doesn't need functionality offered by QApplication, but the event loop is still necessary.

See also QTEST_MAIN().

### QTEST_MAIN(TestClass)

Implements a main() function that instantiates an application object and the TestClass, and executes all tests in the order they were defined. Use this macro to build stand-alone executables.

If `QT_WIDGETS_LIB` is defined, the application object will be a QApplication, if `QT_GUI_LIB` is defined, the application object will be a QGuiApplication, otherwise it will be a QCoreApplication. If qmake is used and the configuration includes `QT += widgets`, then `QT_WIDGETS_LIB` will be defined automatically. Similarly, if qmake is used and the configuration includes `QT += gui`, then `QT_GUI_LIB` will be defined automatically.

Note: On platforms that have keypad navigation enabled by default, this macro will forcefully disable it if `QT_WIDGETS_LIB` is defined. This is done to simplify the usage of key events when writing autotests. If you wish to write a test case that uses keypad navigation, you should enable it either in the `initTestCase()` or `init()` functions of your test case by calling QApplication::setNavigationMode().

Example:

     QTEST_MAIN(TestQString)

See also QTEST_APPLESS_MAIN(), QTEST_GUILESS_MAIN(), QTest::qExec(), and QApplication::setNavigationMode().

### `[since 6.8]` QTEST_THROW_ON_FAIL

When defined, QCOMPARE()/QVERIFY() etc always throw on failure. QTest::setThrowOnFail() then no longer has any effect.

Defining this macro is useful if you wish to use QCOMPARE() or QVERIFY() in functions that have a non-`void` return type. Without this macro defined, QCOMPARE(), for example, expands to a statement including `return;`, so it cannot be used in functions (or lambdas) that return something else than `void`, e.g. QString. This includes the case where throwing exceptions is enabled only at runtime (using QTest::setThrowOnFail(true)). With this macro defined, QCOMPARE() instead expands to a statement without a `return;`, which is usable from any function.

This macro was introduced in Qt 6.8.

### `[since 6.8]` QTEST_THROW_ON_SKIP

When defined, QSKIP() always throws. QTest::setThrowOnSkip() then no longer has any effect.

Defining this macro is useful if you wish to use QSKIP() in functions that have a non-`void` return type. Without this macro defined, QSKIP(), for example, expands to a statement including `return;`, so it cannot be used in functions (or lambdas) that return something else than `void`, e.g. QString. This includes the case where throwing exceptions is enabled only at runtime (using QTest::setThrowOnSkip(true)). With this macro defined, QSKIP() instead expands to a statement without a `return;`, which is usable from any function.

This macro was introduced in Qt 6.8.

### QTRY_COMPARE(actual, expected)

Performs a comparison of the actual and expected values by invoking QTRY_COMPARE_WITH_TIMEOUT() with a timeout of five seconds.

Note: This macro can only be used in a test function that is invoked by the test framework.

See also QTRY_COMPARE_WITH_TIMEOUT(), QCOMPARE(), QVERIFY(), QTRY_VERIFY(), and QEXPECT_FAIL().

### `[since 6.4]` QTRY_COMPARE_EQ(computed, baseline)

Performs comparison of computed and baseline values by invoking QTRY_COMPARE_EQ_WITH_TIMEOUT with a timeout of five seconds.

Note: This macro can only be used in a test function that is invoked by the test framework.

This macro was introduced in Qt 6.4.

See also QCOMPARE_EQ() and QTRY_COMPARE_EQ_WITH_TIMEOUT().

### `[since 6.4]` QTRY_COMPARE_EQ_WITH_TIMEOUT(computed, baseline, timeout)

This macro is similar to QCOMPARE_EQ(), but performs the comparison of the computed and baseline values repeatedly, until either the comparison returns `true` or the timeout (in milliseconds) is reached. Between each comparison, events will be processed. If the timeout is reached, a failure is recorded in the test log and the test won't be executed further.

Since Qt 6.8, the timeout can also be a `std::chrono` literal such as `2s`.

Note: This macro can only be used in a test function that is invoked by the test framework.

This macro was introduced in Qt 6.4.

See also QCOMPARE_EQ() and QTRY_COMPARE_EQ().

### `[since 6.4]` QTRY_COMPARE_GE(computed, baseline)

Performs comparison of computed and baseline values by invoking QTRY_COMPARE_GE_WITH_TIMEOUT with a timeout of five seconds.

Note: This macro can only be used in a test function that is invoked by the test framework.

This macro was introduced in Qt 6.4.

See also QCOMPARE_GE() and QTRY_COMPARE_GE_WITH_TIMEOUT().

### `[since 6.4]` QTRY_COMPARE_GE_WITH_TIMEOUT(computed, baseline, timeout)

This macro is similar to QCOMPARE_GE(), but performs the comparison of the computed and baseline values repeatedly, until either the comparison returns `true` or the timeout (in milliseconds) is reached. Between each comparison, events will be processed. If the timeout is reached, a failure is recorded in the test log and the test won't be executed further.

Since Qt 6.8, the timeout can also be a `std::chrono` literal such as `2s`.

Note: This macro can only be used in a test function that is invoked by the test framework.

This macro was introduced in Qt 6.4.

See also QCOMPARE_GE() and QTRY_COMPARE_GE().

### `[since 6.4]` QTRY_COMPARE_GT(computed, baseline)

Performs comparison of computed and baseline values by invoking QTRY_COMPARE_GT_WITH_TIMEOUT with a timeout of five seconds.

Note: This macro can only be used in a test function that is invoked by the test framework.

This macro was introduced in Qt 6.4.

See also QCOMPARE_GT() and QTRY_COMPARE_GT_WITH_TIMEOUT().

### `[since 6.4]` QTRY_COMPARE_GT_WITH_TIMEOUT(computed, baseline, timeout)

This macro is similar to QCOMPARE_GT(), but performs the comparison of the computed and baseline values repeatedly, until either the comparison returns `true` or the timeout (in milliseconds) is reached. Between each comparison, events will be processed. If the timeout is reached, a failure is recorded in the test log and the test won't be executed further.

Since Qt 6.8, the timeout can also be a `std::chrono` literal such as `2s`.

Note: This macro can only be used in a test function that is invoked by the test framework.

This macro was introduced in Qt 6.4.

See also QCOMPARE_GT() and QTRY_COMPARE_GT().

### `[since 6.4]` QTRY_COMPARE_LE(computed, baseline)

Performs comparison of computed and baseline values by invoking QTRY_COMPARE_LE_WITH_TIMEOUT with a timeout of five seconds.

Note: This macro can only be used in a test function that is invoked by the test framework.

This macro was introduced in Qt 6.4.

See also QCOMPARE_LE() and QTRY_COMPARE_LE_WITH_TIMEOUT().

### `[since 6.4]` QTRY_COMPARE_LE_WITH_TIMEOUT(computed, baseline, timeout)

This macro is similar to QCOMPARE_LE(), but performs the comparison of the computed and baseline values repeatedly, until either the comparison returns `true` or the timeout (in milliseconds) is reached. Between each comparison, events will be processed. If the timeout is reached, a failure is recorded in the test log and the test won't be executed further.

Since Qt 6.8, the timeout can also be a `std::chrono` literal such as `2s`.

Note: This macro can only be used in a test function that is invoked by the test framework.

This macro was introduced in Qt 6.4.

See also QCOMPARE_LE() and QTRY_COMPARE_LE().

### `[since 6.4]` QTRY_COMPARE_LT(computed, baseline)

Performs comparison of computed and baseline values by invoking QTRY_COMPARE_LT_WITH_TIMEOUT with a timeout of five seconds.

Note: This macro can only be used in a test function that is invoked by the test framework.

This macro was introduced in Qt 6.4.

See also QCOMPARE_LT() and QTRY_COMPARE_LT_WITH_TIMEOUT().

### `[since 6.4]` QTRY_COMPARE_LT_WITH_TIMEOUT(computed, baseline, timeout)

This macro is similar to QCOMPARE_LT(), but performs the comparison of the computed and baseline values repeatedly, until either the comparison returns `true` or the timeout (in milliseconds) is reached. Between each comparison, events will be processed. If the timeout is reached, a failure is recorded in the test log and the test won't be executed further.

Since Qt 6.8, the timeout can also be a `std::chrono` literal such as `2s`.

Note: This macro can only be used in a test function that is invoked by the test framework.

This macro was introduced in Qt 6.4.

See also QCOMPARE_LT() and QTRY_COMPARE_LT().

### `[since 6.4]` QTRY_COMPARE_NE(computed, baseline)

Performs comparison of computed and baseline values by invoking QTRY_COMPARE_NE_WITH_TIMEOUT with a timeout of five seconds.

Note: This macro can only be used in a test function that is invoked by the test framework.

This macro was introduced in Qt 6.4.

See also QCOMPARE_NE() and QTRY_COMPARE_NE_WITH_TIMEOUT().

### `[since 6.4]` QTRY_COMPARE_NE_WITH_TIMEOUT(computed, baseline, timeout)

This macro is similar to QCOMPARE_NE(), but performs the comparison of the computed and baseline values repeatedly, until either the comparison returns `true` or the timeout (in milliseconds) is reached. Between each comparison, events will be processed. If the timeout is reached, a failure is recorded in the test log and the test won't be executed further.

Since Qt 6.8, the timeout can also be a `std::chrono` literal such as `2s`.

Note: This macro can only be used in a test function that is invoked by the test framework.

This macro was introduced in Qt 6.4.

See also QCOMPARE_NE() and QTRY_COMPARE_NE().

### QTRY_COMPARE_WITH_TIMEOUT(actual, expected, timeout)

The QTRY_COMPARE_WITH_TIMEOUT() macro is similar to QCOMPARE(), but performs the comparison of the actual and expected values repeatedly, until either the two values are equal or the timeout (in milliseconds) is reached. Between each comparison, events will be processed. If the timeout is reached, a failure is recorded in the test log and the test won't be executed further.

Since Qt 6.8, the timeout can also be a `std::chrono` literal such as `2s`.

Note: This macro can only be used in a test function that is invoked by the test framework.

See also QTRY_COMPARE(), QCOMPARE(), QVERIFY(), QTRY_VERIFY(), and QEXPECT_FAIL().

### QTRY_VERIFY2(condition, message)

Checks the condition by invoking QTRY_VERIFY2_WITH_TIMEOUT() with a timeout of five seconds. If condition is then still false, message is output. The message is a plain C string.

Example:

     QTRY_VERIFY2(list.size() > 2, QByteArray::number(list.size()).constData());

Note: This macro can only be used in a test function that is invoked by the test framework.

See also QTRY_VERIFY2_WITH_TIMEOUT(), QTRY_VERIFY(), QVERIFY(), QCOMPARE(), QTRY_COMPARE(), and QEXPECT_FAIL().

### QTRY_VERIFY(condition)

Checks the condition by invoking QTRY_VERIFY_WITH_TIMEOUT() with a timeout of five seconds.

Note: This macro can only be used in a test function that is invoked by the test framework.

See also QTRY_VERIFY_WITH_TIMEOUT(), QTRY_VERIFY2(), QVERIFY(), QCOMPARE(), QTRY_COMPARE(), and QEXPECT_FAIL().

### QTRY_VERIFY2_WITH_TIMEOUT(condition, message, timeout)

The QTRY_VERIFY2_WITH_TIMEOUT macro is similar to QTRY_VERIFY_WITH_TIMEOUT() except that it outputs a verbose message when condition is still false after the specified timeout (in milliseconds). The message is a plain C string.

Since Qt 6.8, the timeout can also be a `std::chrono` literal such as `2s`.

Example:

     QTRY_VERIFY2_WITH_TIMEOUT(list.size() > 2, QByteArray::number(list.size()).constData(), 10s);

Note: This macro can only be used in a test function that is invoked by the test framework.

See also QTRY_VERIFY(), QTRY_VERIFY_WITH_TIMEOUT(), QVERIFY(), QCOMPARE(), QTRY_COMPARE(), and QEXPECT_FAIL().

### QTRY_VERIFY_WITH_TIMEOUT(condition, timeout)

The QTRY_VERIFY_WITH_TIMEOUT() macro is similar to QVERIFY(), but checks the condition repeatedly, until either the condition becomes true or the timeout (in milliseconds) is reached. Between each evaluation, events will be processed. If the timeout is reached, a failure is recorded in the test log and the test won't be executed further.

Since Qt 6.8, the timeout can also be a `std::chrono` literal such as `2s`.

Note: This macro can only be used in a test function that is invoked by the test framework.

See also QTRY_VERIFY(), QTRY_VERIFY2_WITH_TIMEOUT(), QVERIFY(), QCOMPARE(), QTRY_COMPARE(), and QEXPECT_FAIL().

### QVERIFY2(condition, message)

The QVERIFY2() macro behaves exactly like QVERIFY(), except that it reports a message when condition is false. The message is a plain C string.

The message can also be obtained from a function call that produces a plain C string, such as qPrintable() applied to a QString, which may be built in any of its usual ways, including applying `.args()` to format some data.

Example:

     QVERIFY2(QFileInfo("file.txt").exists(), "file.txt does not exist.");

For example, if you have a file object and you are testing its `open()` function, you might write a test with a statement like:

     bool opened = file.open(QIODevice::WriteOnly);
     QVERIFY(opened);

If this test fails, it will give no clue as to why the file failed to open:

`FAIL! : tst_QFile::open_write() 'opened' returned FALSE. ()`

If there is a more informative error message you could construct from the values being tested, you can use `QVERIFY2()` to pass that message along with your test condition, to provide a more informative message on failure:

     QVERIFY2(file.open(QIODevice::WriteOnly),
              qPrintable(QString("open %1: %2")
                         .arg(file.fileName()).arg(file.errorString())));

If this branch is being tested in the Qt CI system, the above detailed failure message will be inserted into the summary posted to the code-review system:

`FAIL! : tst_QFile::open_write() 'opened' returned FALSE. (open /tmp/qt.a3B42Cd: No space left on device)`

See also QVERIFY(), QCOMPARE(), QEXPECT_FAIL(), QCOMPARE_EQ(), QCOMPARE_NE(), QCOMPARE_LT(), QCOMPARE_LE(), QCOMPARE_GT(), and QCOMPARE_GE().

### QVERIFY(condition)

The QVERIFY() macro checks whether the condition is true or not. If it is true, execution continues. If not, a failure is recorded in the test log and the test won't be executed further.

You can use QVERIFY2() when it is practical and valuable to put additional information into the test failure report.

Note: This macro can only be used in a test function that is invoked by the test framework.

For example, the following code shows this macro being used to verify that a QSignalSpy object is valid:

     QVERIFY(spy.isValid());

For more information about the failure, use `QCOMPARE(x, y)` instead of `QVERIFY(x == y)`, because it reports both the expected and actual value when the comparison fails.

See also QCOMPARE(), QTRY_VERIFY(), QSignalSpy, QEXPECT_FAIL(), QCOMPARE_EQ(), QCOMPARE_NE(), QCOMPARE_LT(), QCOMPARE_LE(), QCOMPARE_GT(), and QCOMPARE_GE().

### `[since 6.3]` QVERIFY_THROWS_EXCEPTION(exceptiontype, ...)

The QVERIFY_THROWS_EXCEPTION macro executes the expression given in the variadic argument and expects to catch an exception thrown from the expression.

There are several possible outcomes:

- If the expression throws an exception that is either the same as exceptiontype or derived from exceptiontype, then execution will continue.
- Otherwise, if the expression throws no exception, or the exception thrown derives from `std::exception`, then a failure will be recorded in the test log and the macro returns early (from enclosing function).
- If the thrown exception derives neither from `std::exception` nor from exceptiontype, a failure will be recorded in the test log, and the exception is re-thrown. This avoids problems with e.g. pthread cancellation exceptions.

The macro uses variadic arguments so the expression can contain commas that the preprocessor considers argument separators, e.g. as in

     QVERIFY_THROWS_EXCEPTION(std::bad_alloc,
     // macro arguments:      ^ exceptiontype
                              std::vector<std::pair<int, long>>{42'000'000'000, {42, 42L}});
     // macro arguments:      \---------- 1 ----------/  \-------- 2 --------/  \3/  \ 4 /
     //                       \----------------------- expression -----------------------/

Note: This macro can only be used in a test function that is invoked by the test framework.

This macro was introduced in Qt 6.3.

### `[since 6.3]` QVERIFY_THROWS_NO_EXCEPTION(...)

The QVERIFY_THROWS_NO_EXCEPTION macro executes the expression given in its variadic argument and tries to catch any exception thrown from the expression.

There are several different outcomes:

- If the expression does not throw an exception, then execution will continue.
- Otherwise, if an exception derived from `std::exception` is caught, a failure will be recorded in the test log and the macro returns early (implicit return from enclosing function).
- If an exception not derived from `std::exception` is caught, a failure will be recorded in the test log and the exception will be re-thrown. This avoids problems with e.g. pthread cancellation exceptions.

The macro uses variadic arguments so the expression can contain commas that the preprocessor considers argument separators, e.g. as in

     QVERIFY_THROWS_NO_EXCEPTION(std::pair<int, long>{42, 42L});
     // macro arguments:         \---- 1 ----/  \-- 2 -/  \3 /

Note: This macro can only be used in a test function that is invoked by the test framework.

This macro was introduced in Qt 6.3.