Qtestlib: QNetworkRequest failed
I would like to test an asynchronous request to a web server. For this, I create a simple unittest to quickly try a few lines of code:
void AsynchronousCall::testGet()
{
QNetworkAccessManager *nam = new QNetworkAccessManager(this);
QUrl url("http://myownhttpserver.org");
QNetworkRequest req(url);
this->connect(nam, SIGNAL(finished(QNetworkReply*)), this, SLOT(reqFinished(QNetworkReply *)));
QNetworkReply *rep = nam->get(req);
}
void AsynchronousCall::reqFinished(QNetworkReply *rep)
{
qDebug() << rep->readAll();
qDebug() << "finshed";
}
The problem is that reqFinished () is never reached. If I had a simple QEventLoop and an .exec () loop right after nam-> get (req); the request is being executed.
Any hint? Should I use loop.exec () in my unittests?
+2
a source to share
1 answer
If you want to test asynchronous behavior, you need to use QEventLoop or another class with similar functionality. I suggest you write a helper method like this:
bool waitForSignal(QObject *sender, const char *signal, int timeout = 1000) {
QEventLoop loop;
QTimer timer;
timer.setInterval(timeout);
timer.setSingleShot(true);
loop.connect(sender, signal, SLOT(quit()));
loop.connect(&timer, SIGNAL(timeout()), SLOT(quit()));
timer.start();
loop.exec();
return timer.isActive();
}
Then you can use it in your unit tests like this:
void AsynchronousCall::testGet()
{
QNetworkAccessManager *nam = new QNetworkAccessManager(this);
QUrl url("http://myownhttpserver.org");
QNetworkRequest req(url);
this->connect(nam, SIGNAL(finished(QNetworkReply*)), this, SLOT(reqFinished(QNetworkReply *)));
QNetworkReply *rep = nam->get(req);
QVERIFY(waitForSignal(nam, SIGNAL(finished(QNetworkReply*)), 5000));
}
There are other problems in your test:
- Tests that depend on network connectivity do not need to be modular. You want your unit tests to fire up quickly, which is impossible to achieve with network connections.
- Your test doesn't actually test anything: it just puts some information into the debug console. You must define expectations and test them using the QVERIFY and QCOMPARE macros.
- QTest sucks IMHO. If you're building a testbase from scratch, start using gtest + gmock instead.
+13
a source to share