2 KiB
title | date | draft | tags | series | summary | ||
---|---|---|---|---|---|---|---|
Obscure Qt: Testing log messages | 2025-04-15 | false |
|
|
I noticed that I kept searching for "how do I check for log messages in Qt tests?" online. I figure that is a good enough indicator for "obscure" and now deserves to be saved on my blog |
I noticed that I kept searching for "how do I check for log messages in Qt tests?" online. I figure that is a good enough indicator for obscurity1 and now deserves to be saved on my blog!
The case that spurred this is me writing a bunch of fallible code recently, and I wanted to check if the log message is emitted. Since the message also dynamic, making sure it has the correct line number too. For reference, here is some sample code:
const auto node = childNode.firstChildElement(QStringLiteral("SomeNode"));
if (node.isNull()) {
qWarning() << "Missing <SomeNode> for node at line" << childNode.lineNumber();
return std::nullopt;
}
...
Checking if this returns std::nullopt
is easy enough, but what about the log output? It turns out QTest has us covered here with QTest::ignoreMessage. Add it to your test case, and it will panic if the message is not emitted:
QTest::ignoreMessage(QtWarningMsg, "Missing <SomeNode> for node at line 14");
And if the message isn't emitted, it will complain in your test output:
INFO : ConfigFileTest::scaleUpData() Did not receive message: "Missing <SomeNode> for node at line 14"
FAIL! : ConfigFileTest::scaleUpData() Not all expected messages were received
However if the message is found, it hides said message from the test output which is extremely useful too. Also useful to know is that there's a RegExp overload if you don't want it to be as specific.
-
Out of pure curiosity, I checked the KDE repositories and there's only ~60 usages of this function. I hope to see more of this the next time I check! ↩︎