我正在尝试为我编写的 Qt5 应用程序编写单元测试,但我对如何处理涉及网络的类感到困惑。我的主类包括一个 QTcpServer 子类,它覆盖 QTcpServer::incomingConnection 以创建一个 ClientConnection 对象并将其交给一个线程:
void NetworkServer::incomingConnection(qintptr socketDescriptor)
{
QThread* clientThread = new QThread();
ClientConnection* clientConnection = new ClientConnection(socketDescriptor);
clientConnection->moveToThread(clientThread);
// connect signals & slots to ClientConnection (removed for clarity)
connect(clientThread, &QThread::started, clientConnection, &ClientConnection::run);
clientThread->start();
}
ClientConnection 类使用 socketDescriptor 在专用线程中打开一个新的 QTcpSocket,从客户端接收数据,并对其进行处理。
ClientConnection::ClientConnection(int socketDescriptor, QObject *parent) :
QObject(parent), socketDescriptor(socketDescriptor)
{
tcpIncomingData = new QByteArray;
}
void ClientConnection::run()
{
QTcpSocket socket;
if(!socket.setSocketDescriptor(socketDescriptor)) {
emit sig_error(socket.error());
return;
}
if(socket.waitForReadyRead(5000)) {
*tcpIncomingData = socket.readAll();
qDebug() << "data received: " << tcpIncomingData;
} else {
qDebug() << "socket timed out!";
}
parseXmlData();
socket.disconnectFromHost();
socket.waitForDisconnected();
}
这门课还没有结束,但我现在想开始写测试。我的问题是如何处理socketDescriptor。我假设我需要使用某种依赖注入,但如果不在测试用例中创建整个 QTcpServer,我认为这是不可行的。
这些天来测试网络代码一定很常见,所以必须有一种通用的方法来处理这个问题,而不包括我的一半应用程序。这似乎是一个普遍的问题,但如果需要有关我的特定应用程序的更多详细信息,请告诉我。