c++qtunit-testingqttest

Qt unit testing: QCOMPARE function on list of pointers


Does Qt testing framework support comparing list of pointers or I am doing something wrong?

My unit test source is as follows:

QList<QString *> list1;
QList<QString *> list2;

list1.append(new QString("test"));
list2.append(new QString("test"));

QCOMPARE(list1, list2);

After running this test, I was expecting passed test, but test failed with following output:

********* Start testing of ConfigurationTest *********
Config: Using QtTest library 5.5.1, Qt 5.5.1 (x86_64-little_endian-lp64 shared (dynamic) release build; by GCC 5.4.0 20160609)
FAIL!  : ConfigurationTest::test_sample(default) Compared lists differ at index 0.
   Actual   (list1): <null>
   Expected (list2): <null>
   Loc: [../unittest/sample_test.cpp(32)]
Totals: 0 passed, 1 failed, 0 skipped, 0 blacklisted
********* Finished testing of ConfigurationTest *********

If list contains non-pointer elements, QCOMPARE does not have any issues with it and returns "passed" output.


Solution

  • In the docs you can read that QCOMPARE uses a comparison operator for comparing values:

    The QCOMPARE macro compares an actual value to an expected value using the equals operator.

    QList also works in the same way.

    This implies that if your list stores pointers, pointer comparison operators are used, not the comparison operators of the underlying objects (i.e. values of pointers are compared, not the values of the objects pointed to). Pointers compare equal when they point to the same object, and in your case you have two different objects, so they are not equal, even if the contents of the objects are identical.

    So the answers is: QCOMPARE does support comparing lists of pointers - it just doesn't work the way you expected. The rules of pointers comparison are described in detail here.