目录
官方手册:<QTest> 的宏:QCOMPARE(actual, expected)
========================================
官方手册:<QTest> 的宏:QCOMPARE(actual, expected)
QTest Namespace
The QTest namespace contains all the functions and declarations that are related to Qt Test. More...
Header:
#include <QTest>
qmake:
QT += testlib
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.
When comparing floating-point types (float, double, and qfloat16), qFuzzyCompare() is used for finite values. 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). This means that expecting 0 can fail when the actual value may be affected by rounding errors. One solution to this is to offset both actual and expected values by adding some suitable constant (such as 1).
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"));
Note: This macro can only be used in a test function that is invoked by the test framework.
For your own classes, you can use QTest::toString() to format values for outputting into the test log.
Example:
namespace QTest {
template <> char *toString<MyType>(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(), and QEXPECT_FAIL().