1

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.

franz
  • 312
  • 3
  • 15

1 Answers1

3

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.

KjMag
  • 2,650
  • 16
  • 16
  • Thanks KjMag for quick answer. I get it now. Actually, this won't help me much as I am appending elements to lists on different locations in source, so they are completely different objects but tests has to confirm that they contain same values inside. I will need to go with different approach and take out values from pointers before comparing them. Once again thanks! – franz Aug 07 '17 at 13:22
  • 1
    No problem. If you really need to have pointers, consider writing an object that would wrap a pointer and define custom comparison operator so that it compares the values pointed to by the internal pointer, not the value of the pointer itself. – KjMag Aug 07 '17 at 13:28