Details
-
Suggestion
-
Resolution: Done
-
Not Evaluated
-
None
-
None
-
None
-
658b9697f9d85d4ed294810b4f60bafdbdd8e247 (qt/qtbase/dev)
Description
Often I want to construct a useful message for test failures by including a textual representation of an object involved with the failure. Creating such a message is easy when using QDebug, because I can just use my existing operator<< for that object's type, but the QTest framework requires a string. This results in code like the following:
if (!list.isEmpty()) { QString message; QDebug debug(&message); debug << "Expected list to be empty, but it still contains the following items:" << list; QFAIL(qPrintable(message)); }
This is even worse for checks that must be repeated over time, as there is no simple way to do the above test without the QTRY_* macros.
What I recently did was define a toString() template function that simply stores the result of calling operator<< with the object and returns it:
template <typename T> QString toString(const T &object) { QString buffer; QDebug stream(&buffer); stream << object; return buffer; }
It can then be used like this:
QTRY_VERIFY2(list.isEmpty(), qPrintable(QString::fromLatin1(
"Expected list to be empty, but it still contains the following items: %1").arg(QtUtils::toString(list))));
I think that this would be a really convenient addition for debug output in tests, and possibly other places where strings are required.
QTest already has a toString API that is only used for printing types in failures in its macros, otherwise that could have also been a good place to add the proposed function.
Attachments
For Gerrit Dashboard: QTBUG-82309 | ||||||
---|---|---|---|---|---|---|
# | Subject | Branch | Project | Status | CR | V |
291156,8 | Add QDebug::toString() | dev | qt/qtbase | Status: MERGED | +2 | 0 |