简体   繁体   中英

Qt testing when dependent on Network

I'm working on a Qt project, and I need to be able to write unit tests for functions that depend on QNetworkAccessManager.

Google Mock seems like an overkill for my purposes, and I found this answer which suggest using a "linker trick" to mock the class. However, I'm very new to C++ (and C in general), and I'm having somewhat hard time in understanding the exact way I'm supposed to use this "trick". Am I supposed to manually change the header file to run the test, or is there some nicer way to do it (I'm assuming there is).

Any kind of an example on the header/code structure to do this correctly would be an immense help.

You could use linker tricks, but as QNetworkAccessManager can be subclassed, you might find it easier just to do that.

For example, if you want to make a version that doesn't actually connect, you could do something like:

class FailQNetworkAccessManager : public QNetworkAccessManager
{
  Q_OBJECT
public:
  FailQNetworkAccessManager(QObject *parent = Q_NULLPTR):QNetworkAccessManager(parent){}

protected:
  QNetworkReply* createRequest(Operation op, const QNetworkRequest &originalReq, QIODevice *outgoingData = Q_NULLPTR)
  {
    QNetworkReply* rep = QNetworkAccessManager::createRequest(op, originalReq, outgoingData);
    // Queue the abort to occur from main loop
    QMetaObject::invokeMethod(req, "abort", Qt::QueuedConnection);
    return rep;
  }
};

Then your test code can provide your class with the FailQNetworkAccessManager rather than the real one, and all requests should abort as soon as they're created. (This is just example code, I haven't actually tried this code yet - I would also recommend splitting this into header & cpp files).

You should also have a look at the Qt Test system, which is the built in test framework.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM