Important: Please read the Qt Code of Conduct -

How to run async serial in tests?

  • Hello,

    I'm trying to run asynchronous serial ports in Qt Test (on Windows 10). Here's the test (edited by suggestion of SGaist):

    void test_serial::test_serial()
        QSerialPort serialPortWrite;
            QSerialPort serialPortRead;
            SerialPortWriter writer(&serialPortWrite);
            SerialPortReader reader(&serialPortRead);
            QSignalSpy spy(&serialPortWrite, &QSerialPort::bytesWritten);
            QByteArray arr = {"asdfasdf"};
            qDebug() << spy.count();
            QTEST_ASSERT(arr == reader.m_readData);}

    SerialPortWriter and SerialPortReader are asynchronous serial writer and reader classes taken from QT creator's examples ("Command line reader async example" and "Command line writer async example"). I just changed m_readData of SerialPortReader to public. I have created and connected COM11 and COM12 together with com0com (found here: with commands:

    setupc install PortName=COM# PortName=COM#
    setupc change CNCA0 RealPortName=COM11
    setupc change CNCB0 RealPortName=COM12

    Spy.count() prints 0, so the signal never gets emitted. So SerialPortWriter::handleBytesWritten never gets called. This is a handler for bytesWritten signal of QSerialPort.

    When I run the examples as their own, they run fine. I have checked that SerialPortWriter works with a serial port client (ScriptCommunicator in my case).

    How do you run asynchronous serial ports in Qt tests?


  • Lifetime Qt Champion

    What type of test main function are you running ?

  • Lifetime Qt Champion


    One thing that is missing from your test is the checks to ensure the ports have been opened successfully.

    You might also need to flush them.

    You should also add some QSignalSpy to ensure the appropriate signals are called.

  • @SGaist Edited the test by your suggestion. Ports are open, but the signal never gets emitted. Weird.

  • Lifetime Qt Champion

    What type of test main function are you running ?

  • Ah, very good. Thank you. It was QTEST_APPLESS_MAIN. I changed it to QTEST_MAIN and the test now passes.

  • Qt Champions 2020

    Look how does it work, e.g. in the QSP sources, there are present the tests/auto directory with the tests.

Log in to reply