|  | Home · All Classes · Main Classes · Grouped Classes · Modules · Functions |

# QTest Namespace Reference
[QtTest module]

The QTest namespace contains all the functions and declarations that are related to the QTestLib tool. More...

     #include <QTest>

### Types

- enum KeyAction { Press, Release, Click }
- enum MouseAction { MousePress, MouseRelease, MouseClick, MouseDClick, MouseMove }
- enum SkipMode { SkipSingle, SkipAll }
- enum TestFailMode { Abort, Continue }

### Functions

- void addColumn ( const char * name, T * dummy = 0 )
- const char * currentDataTag ()
- bool currentTestFailed ()
- const char * currentTestFunction ()
- void ignoreMessage ( QtMsgType type, const char * message )
- 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 keyClicks ( QWidget * widget, const QString & sequence, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1 )
- void keyEvent ( KeyAction action, QWidget * widget, Qt::Key key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1 )
- void keyEvent ( KeyAction action, QWidget * widget, 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 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 mouseClick ( QWidget * widget, Qt::MouseButton button, Qt::KeyboardModifiers modifier = 0, QPoint pos = QPoint(), int delay = -1 )
- void mouseDClick ( QWidget * widget, Qt::MouseButton button, Qt::KeyboardModifiers modifier = 0, QPoint pos = QPoint(), int delay = -1 )
- void mouseMove ( QWidget * widget, QPoint pos = QPoint(), int delay = -1 )
- void mousePress ( QWidget * widget, Qt::MouseButton button, Qt::KeyboardModifiers modifier = 0, QPoint pos = QPoint(), int delay = -1 )
- void mouseRelease ( QWidget * widget, Qt::MouseButton button, Qt::KeyboardModifiers modifier = 0, QPoint pos = QPoint(), int delay = -1 )
- QTestData & newRow ( const char * dataTag )
- int qExec ( QObject * testObject, int argc = 0, char ** argv = 0 )
- void qSleep ( int ms )
- void qWait ( int ms )
- char * toHexRepresentation ( const char * ba, int length )
- char * toString ( const T & value )
- char * toString ( const QLatin1String & string )
- char * toString ( const QString & string )
- char * toString ( const QByteArray & ba )
- char * toString ( const QTime & time )
- char * toString ( const QDate & date )
- char * toString ( const QDateTime & dateTime )
- char * toString ( const QChar & character )
- char * toString ( const QPoint & point )
- char * toString ( const QSize & size )
- char * toString ( const QRect & rectangle )
- char * toString ( const QPointF & point )
- char * toString ( const QSizeF & size )
- char * toString ( const QRectF & rectangle )

### Macros

- QCOMPARE ( actual, expected )
- QEXPECT_FAIL ( dataIndex, comment, mode )
- QFAIL ( message )
- QFETCH ( type, name )
- QSKIP ( description, mode )
- QTEST ( actual, testElement )
- QTEST_APPLESS_MAIN ( TestClass )
- QTEST_MAIN ( TestClass )
- QTEST_NOOP_MAIN ()
- QVERIFY2 ( condition, message )
- QVERIFY ( condition )
- QWARN ( message )

## Detailed Description

The QTest namespace contains all the functions and declarations that are related to the QTestLib tool.

Please refer to the QTestLib Manual documentation for information on how to write unit tests.

## 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).

### 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::SkipMode

This enum describes the modes for skipping tests during execution of the test data.

Constant | Value | Description
--- | --- | ---
`QTest::SkipSingle` | `1` | Skips the current entry in the test table; continues execution of all the other entries in the table.
`QTest::SkipAll` | `2` | Skips all the entries in the test table; the test won't be executed further.

See also QSKIP().

### enum QTest::TestFailMode

This enum describes the modes for handling an expected failure of the QVERIFY() or QCOMPARE() macros.

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 expected failure.
`QTest::Continue` | `2` | Continues execution of the test after the expected failure.

See also QEXPECT_FAIL().

## Function Documentation

### 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:

     void myTestFunction_data() {
         QTest::addColumn<int>("intval");
         QTest::addColumn<QString>("str");
         QTest::addColumn<double>("dbl");

         QTest::newRow("row1") << 1 << "hello" << 1.5;
     }

To add custom types to the testdata, the type must be registered with QMetaType via Q_DECLARE_METATYPE().

Note: This macro can only be used in 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.

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

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

### bool QTest::currentTestFailed ()

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

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

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

Example:

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

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

Ignores messages created by qDebug() 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 outputted 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.

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

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

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` with a following 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 ) `[static]`

This is an overloaded member function, provided for convenience.

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

Example:

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

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

See also QTest::keyClicks().

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

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 ( KeyAction action, QWidget * widget, Qt::Key key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1 ) `[static]`

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 ( KeyAction action, QWidget * widget, char ascii, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay = -1 ) `[static]`

This is an overloaded member function, provided for convenience.

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.

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

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

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 ) `[static]`

This is an overloaded member function, provided for convenience.

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

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

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

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

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

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

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

This is an overloaded member function, provided for convenience.

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

See also QTest::keyClick().

### void QTest::mouseClick ( QWidget * widget, Qt::MouseButton button, Qt::KeyboardModifiers modifier = 0, 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::mouseDClick ( QWidget * widget, Qt::MouseButton button, Qt::KeyboardModifiers modifier = 0, 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::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::mousePress ( QWidget * widget, Qt::MouseButton button, Qt::KeyboardModifiers modifier = 0, 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::mouseRelease ( QWidget * widget, Qt::MouseButton button, Qt::KeyboardModifiers modifier = 0, 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.

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

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

Appends a new row to the current test data. dataTag is the name of the testdata that will appear in the test output. Returns a QTestData reference that can be used to stream in data.

Example:

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

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

See Data Driven Testing for a more extensive example.

See also addColumn() and QFETCH().

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

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 QTestLib Command Line Arguments.

For stand-alone tests, the convenience macro QTEST_MAIN() can be used to declare a main method that parses the command line arguments and executes the tests.

The following example will run all tests in `MyFirstTestObject` and `MySecondTestObject`:

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

     MySecondTestObject test2;
     QTest::qExec(&test2);

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.

See also QTEST_MAIN().

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

Sleeps for ms milliseconds, blocking execution of the test. qSleep() will not do any event processing and leave your test unresponsive. Network communication might time out while sleeping. Use qWait() to do non-blocking sleeping.

ms must be greater than 0.

Note: The qSleep() function calls either `nanosleep()` on unix or `Sleep()` on windows, so the accuracy of time spent in qSleep() depends on the operating system.

Example:

     QTest::qSleep(250);

See also qWait().

### void QTest::qWait ( int ms ) `[static]`

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

Example:

     int i = 0;
     while (myNetworkServerNotResponding() && i++ < 50)
         QTest::qWait(250);

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

See also QTest::qSleep().

### char * QTest::toHexRepresentation ( const char * ba, int 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.

length is the length of the string ba.

### 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 of this function to your test to enable verbose output.

Note: The caller of toString() must delete the returned data using `delete[]`. Your implementation should return a string created with `new[]` or qstrdup().

Example:

     namespace QTest {
         template<>
         char *toString(const MyPoint &point)
         {
             QByteArray ba = "MyPoint(";
             ba += QByteArray::number(point.x()) + ", " + QByteArray::number(point.y());
             ba += ")";
             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.

See also QCOMPARE().

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

This is an overloaded member function, provided for convenience.

Returns a textual representation of the given string.

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

This is an overloaded member function, provided for convenience.

Returns a textual representation of the given string.

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

This is an overloaded member function, provided for convenience.

Returns a textual representation of the byte array ba.

See also QTest::toHexRepresentation().

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

This is an overloaded member function, provided for convenience.

Returns a textual representation of the given time.

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

This is an overloaded member function, provided for convenience.

Returns a textual representation of the given date.

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

This is an overloaded member function, provided for convenience.

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

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

This is an overloaded member function, provided for convenience.

Returns a textual representation of the given character.

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

This is an overloaded member function, provided for convenience.

Returns a textual representation of the given point.

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

This is an overloaded member function, provided for convenience.

Returns a textual representation of the given size.

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

This is an overloaded member function, provided for convenience.

Returns a textual representation of the given rectangle.

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

This is an overloaded member function, provided for convenience.

Returns a textual representation of the given point.

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

This is an overloaded member function, provided for convenience.

Returns a textual representation of the given size.

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

This is an overloaded member function, provided for convenience.

Returns a textual representation of the given rectangle.

## Macro Documentation

### QCOMPARE ( actual, expected )

The QCOMPARE macro compares an actual value to an expected value using the equals operator. If actual and expected are identical, execution continues. If not, a failure is recorded in the test log and the test won't be executed further.

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.

Note: QCOMPARE is very strict on the data types. Both actual and expected have to be of the same type, otherwise the test won't compile. This prohibits unspecified behavior from being introduced; that is behavior that usually occurs when the compiler implicitely casts the argument.

Note that, for your own classes, you can use QTest::toString() to format values for outputting into the test log.

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

Example:

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

See also QVERIFY() and QTest::toString().

### 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.

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.

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`.

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. name has to match the element name from the test's data. If no such element exists, the test will assert.

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.

### QSKIP ( description, mode )

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. The text description is appended to the test log and should contain an explanation why the test couldn't be executed. mode is a QTest::SkipMode and describes whether to proceed with the rest of the test data or not.

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

Example:

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

See also QTest::SkipMode.

### 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_MAIN ( TestClass )

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

Example:

     class TestQString: public QObject { ... };
     QTEST_MAIN(TestQString)

See also QTEST_APPLESS_MAIN() and QTest::qExec().

### QTEST_NOOP_MAIN ()

Implements a main() function with a test class that does absolutely nothing. Use this macro to create a test that produces valid test output but just doesn't execute any test, for example in conditional compilations:

     #ifdef Q_WS_X11
         QTEST_MAIN(MyX11Test)
     #else
         // do nothing on non-X11 platforms
         QTEST_NOOP_MAIN
     #endif

See also QTEST_MAIN().

### QVERIFY2 ( condition, message )

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

Example:

     QVERIFY2(1 + 1 == 2, "A breach in basic arithmetic occured.");

See also QVERIFY() and QCOMPARE().

### 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.

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

Example:

     QVERIFY(1 + 1 == 2);

See also QCOMPARE().

### QWARN ( message )

Appends message as a warning to the test log. This macro can be used anywhere in your tests.

Note: This function is thread-safe.