2

I have been developing a client-server library using C++/Qt and I have written separate programs that run properly. Now I want to test this using Qt's unit test framework. So far I have written the client code, but it doesn't work properly. sometimes it doesn't connect to server and when it connects the data it sends is null.

class JsonRPCServerTest : public QObject {
    Q_OBJECT

public:
    JsonRPCServerTest(QObject* parent = nullptr);
    ~JsonRPCServerTest();

private Q_SLOTS:
    void initTestCase();
    void client();
    void cleanupTestCase();
private :
    JsonRPCClient m_client;
};

JsonRPCServerTest::JsonRPCServerTest(QObject* parent):
    QObject(parent) {
}

void JsonRPCServerTest::client() {
    m_client.setUrl(QUrl("http://127.0.0.1:8383"));
    int i = 1;
    QJsonObject jobj;
    jobj["x"] = i;
    jobj["y"] = i;
    JsonRPCRequest req(1, "sum", jobj);
    qDebug() << "Dispatching " << req.data();
    m_client.dispatch(req);
    qApp->processEvents();
}

QTEST_GUILESS_MAIN(JsonRPCServerTest)

#include "tst_jsonrpcserver.moc"
Roya Ghasemzadeh
  • 673
  • 5
  • 16
  • Why do you call processEvents there? You generally shouldn't call it, it can lead to all kinds of funny behavior due to re-entrancy issues. – hyde Feb 09 '19 at 16:14
  • Earlier I hadn't add that line, but the client never connected to server. Then I searched a bit and I found [this](https://stackoverflow.com/questions/6433933/qtcpclient-successfully-connects-but-not-to-my-server-where-is-it-connecting) , so I called processEvents and the result was as I described above. – Roya Ghasemzadeh Feb 09 '19 at 17:23
  • processEvents will only process the events currently in queue, then return. Normally you want the event loop rolling. But this is test code, and I haven't used QTest so not quite sure how you should go about it. But in general, in unit tests you usually don't have network connections etc. If you do, you aren't doing unit tests any more. – hyde Feb 09 '19 at 21:15
  • I deleted the processEvents call and added QTest::qWait(10000) in client slot and now it seems to works fine. thanks for your comments. – Roya Ghasemzadeh Feb 10 '19 at 08:41

0 Answers0