Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. How to Create Unit Test for QTcpServer and Mocking QUdpSocket?
Forum Updated to NodeBB v4.3 + New Features

How to Create Unit Test for QTcpServer and Mocking QUdpSocket?

Scheduled Pinned Locked Moved Unsolved General and Desktop
2 Posts 2 Posters 443 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • D Offline
    D Offline
    DJViking
    wrote on last edited by DJViking
    #1

    I want to create unit tests on some business logic, not any GUI UI code.

    I have a class that extends QTcpServer, which uses a QUdpSocket to send messages to another server. What I need to test is the message the server sends to the other server is correct.

    How can I create a Mock of this QUdpSocket? I am using Google Test as my testing framework.

    my_tcp_server.h

    class MyTcpServer : public QTcpServer
    {
      Q_OBJECT
    public:
      explicit MycpServer(QObject *parent = 0);
      ~MyTcpServer();
    
    private:
        qint64  sendMessage(QSslSocket *sslSocket, const char *buff);
        QUdpSocket socket;
    };
    

    my_tcp_server.cpp

    MyTcpServer::MyTcpServer(QObject *parent) 
        : QTcpServer(parent)
    {
        socket.bind();
    }
    
    qint64 MyTcpServer::sendMessage(QSslSocket *sslSocket, const char *buff)
    {
        qint64 returnValue = 0;
    
        MessageStruct message;
        message.value1 =*((unsigned int*) buff); buff+=4;
        message.value2 =*((unsigned int*) buff); buff+=4;
        message.value3 =*((unsigned int*) buff); buff;
    
        qint64 returnValue = socket.writeDatagram((const char *) &message, sizeof(MessageStruct), QHostAddress(HOST), PORT);
    }
    

    The message is constructed of the content in the byte buffer coming from the client connected to the QTcpServer.

    What I need to test is that this message is correct, but I do not want to send this message to any socket.

    1 Reply Last reply
    0
    • SGaistS Offline
      SGaistS Offline
      SGaist
      Lifetime Qt Champion
      wrote on last edited by
      #2

      Hi,

      The usual way would be to make QUdpSocket a pointer and add a setter to your class so you can change the QUdpSocket for something else.

      Interested in AI ? www.idiap.ch
      Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

      1 Reply Last reply
      0

      • Login

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • Users
      • Groups
      • Search
      • Get Qt Extensions
      • Unsolved