Suppress qDebug when using QTestLib

c++, qt, unit-testing

Solution

The `QT_NO_DEBUG_OUTPUT` define must go into your project files or makefiles and must be present for every file you compile. You must then recompile your application (not Qt itself of course). This macro's presence on compiler's command line guarantees that the first time `QDebug` header is included by any code, the `qDebug` will be redefined to a no-op. That's what this macro does: it disables `qDebug` if it is present when the `<QtCore/qdebug.h>` header gets included -- whether directly by you or indirectly by other headers.

Using `qInstallMsgHandler` certainly works at suppressing debug output.

Below is a self-contained example.

#if 0
// Enabling this section disables all debug output from non-Qt code.
#define QT_NO_DEBUG_OUTPUT
#endif
#include <QtCore/QDebug>

void noMessageOutput(QtMsgType, const char *)
{}

int main(int argc, char *argv[])
{
    qDebug() << "I'm shown";
    qInstallMsgHandler(noMessageOutput);
    qDebug() << "I'm hidden";
}

Problem

I am adding unit tests to project in Qt and am looking to use QTestLib. I have set up the tests and they are running fine. The issue is that in the project we have overridden qDebug() to output to our own log file. This works great when running the app, the problem is that when I am testing the classes, it will sometimes start logging, which is then sent to the output window. The result is a complete disaster that is next to impossible to read as our logs get mixed in with the QTest output. I am wondering if there is a way to suppress the qDebug() output, or at least move it somewhere else. I have tried adding `#define QT_NO_DEBUG_OUTPUT` and also using `qInstallMsgHandler(messageOutput);` to redirect or prevent the output, but neither had any effect.

Original source