user1029083
user1029083

Reputation: 191

QTestLib unit test framework + Gmock (Create QTCPServer - Mock Object)

I am using Qt's QTestLib unit test framework + GMOck.

I am trying to set up mock server using gMock to simply receive data from a QTcpSocket to VerifySendData() method in a unit test.

If someone would give me a example how I can create mock object gMOCK (EXPECT CALL, create Mock Object)

#ifndef TST_TCPCOMMTEST_H
#define TST_TCPCOMMTEST_H

#include <QtCore/QString>
#include <QtTest/QtTest>
#include <QTcpSocket>
#include <QTcpServer>

class TcpCommTest : public QObject
{
    Q_OBJECT

private:
    QTcpSocket* pTestSocket;
    QTcpSocket* pMockSocket;
    QTcpServer* pMockServer;

public:
        TcpCommTest();

public slots:
    void connectMockServer();

private Q_SLOTS:
    void initTestCase();    
    void VerifySendData();    
    void cleanupTestCase();
};

#endif // TST_TCPCOMMTEST_H





#include "tst_tcpcommtest.h"
#include <QtDebug>
#include <QtCore/>
#include <QtTest/QtTest>
#include <QtNetwork/QtNetwork>
#include <gmock/gmock.h>


void TcpCommTest::connectMockServer()
{
    cout << "connection attempt" << endl;
    pMockSocket = pMockServer->nextPendingConnection();
}

void TcpCommTest::initTestCase()
{
    pMockSocket = NULL;
    pMockServer = new QTcpServer();

    //I want to use gMock here to create MockTCP Server
    EXPECT_CALL(pMockServer,someMethod(1).Times(AtLeaset(1));
     EXPECT_CALL(pMockServer,someMethod(2).Times(AtLeaset(1));
    //pMockServer->listen( QHostAddress("127.0.0.1"), 2000 );
    //connect( pMockServer, SIGNAL(newConnection()), SLOT(connectMockServer()) );

    pTestSocket = new QTcpSocket();
    pTestSocket->connectToHost( QHostAddress("127.0.0.1"), 2000 );

    QVERIFY( pTestSocket->waitForConnected( 1000 ) );
    QVERIFY( pTestSocket->state() == QTcpSocket::ConnectedState );
}

void TcpCommTest::VerifySendData()
{
    int i=0;
    QVERIFY( pMockSocket != NULL );
}

QTEST_MAIN(TcpCommTest);

Upvotes: 4

Views: 2118

Answers (1)

Dorian
Dorian

Reputation: 417

I do not have enough reputation to comment, but I don't know what you want to achieve exactly. You app that you try to test is host or client?

Anyway, you cannot call:

pMockServer = new QTcpServer();
EXPECT_CALL(pMockServer,someMethod(2))

pMockServer must have mocked someMethod by a MOCK_METHOD1 macro. If someMethod is virtual in QTcpServer, then QTcpServerMock can derive from QTcpServer and just have

MOCK_METHOD1(someMethod, void(int))

If not all methods, that you want to mock are virtual, then you cannot override it with MOCK_METHOD1. I would create TcpServerInterface that is derived by TcpServer and TcpServerMock. someMethod would be virtual in TcpServerInterface, implemented for real in TcpServer and mocked by macro in TcpServerMock. Real TcpServer can have QTcpServer as private member and just wrap it.

Upvotes: 0

Related Questions