我目前正在为我的一门课程编写一些单元测试。但是,我很快遇到了一个问题。似乎 QSignalSpy 有时无法捕捉到我的班级disconnected()
发出的信号。Client
这是我的单元测试:
void ClientTest::test_disconnectFromHost()
{
QTcpServer server;
server.listen(QHostAddress::Any, 65000);
QTcpSocket* clientSocket = new QTcpSocket();
QSignalSpy connectedSpy(clientSocket, SIGNAL(connected()));
clientSocket->connectToHost(QHostAddress::Any, 65000);
if (!connectedSpy.wait()) {
QFAIL("Client socket connection failed.");
}
Chat::Client client(clientSocket);
QSignalSpy disconnectedSpy(clientSocket, SIGNAL(disconnected()));
// Return true if disconnection succeded
QVERIFY(client.disconnectFromHost());
QVERIFY(disconnectedSpy.wait(500)); // RETURNS FALSE!
// Return false if client was not connected
QVERIFY(!client.disconnectFromHost());
QCOMPARE(client.getLastError(),
Chat::Client::Error::NotConnected);
clientSocket->connectToHost(QHostAddress::Any, 65000);
if (!connectedSpy.wait()) {
QFAIL("Client socket connection failed.");
}
QTcpSocket* serverSocket = server.nextPendingConnection();
serverSocket->disconnectFromHost(); // RETURNS FALSE!
// Emit disconnected if the server closed the connection
QVERIFY(disconnectedSpy.wait(500));
delete serverSocket;
}
以下是相关的类方法:
Client::Client(QTcpSocket* socket, QObject* parent)
: QObject(parent)
{
this->socket = socket;
messageSize = -1;
lastError = None;
lastErrorString = "";
connect(socket, SIGNAL(connected()), this, SLOT(onSocketConnected()));
connect(socket, SIGNAL(disconnected()), this, SLOT(onSocketDisconnected()));
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(onSocketError(QAbstractSocket::SocketError)));
connect(socket, SIGNAL(readyRead()), this, SLOT(onDataReceived()));
}
bool Client::connectToHost(const QHostAddress& serverAddress, quint16 serverPort)
{
if (socket->state() != QTcpSocket::SocketState::UnconnectedState) {
lastError = AlreadyConnected;
return false;
}
messageSize = -1;
socket->connectToHost(serverAddress, serverPort);
return true;
}
bool Client::disconnectFromHost()
{
if (socket->state() != QTcpSocket::SocketState::ConnectedState) {
lastError = NotConnected;
return false;
}
socket->disconnectFromHost();
return true;
}
void Client::onSocketConnected()
{
emit connected();
}
void Client::onSocketDisconnected()
{
emit disconnected();
}
[...]
有没有人解释为什么 QSignalSpy.wait() 方法返回 false,即使通过调试单元测试,我知道disconnected()
信号已发出?
谢谢!