RSSAmplifier

redstrate's Blog · Apr 15, 2025

Obscure Qt: Testing log messages

0
Sign in to vote or save

redstrate · redstrate.com

Posted on
Tags: Qt

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.


  1. 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! ↩︎

Share on Mastodon!

See Also #

Read the original on redstrate.com

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.