I have a client-server system based on TCP coded in C#. I was requested to add a bidirectional heartbeat to discover if any of the elements in the network freeze and are not responding.
I solved the problem by sending a heartbeat from the server to all connected clients and waiting for the response. There's a timeout if the response doesn't come on time and there is a timeout in the clients if the server didn't send any heartbeat in 2 seconds (assuming the server is frozen).
Everything happens internally and the server nor the client expose any of the events (receiving a heartbeat, replying a heartbeat happen silently, as it was requested)
The thing is .. How does one create a unit test or integration test for such a functionality?
Note: I'm coding in visual studio, C#, .Net 4.6.1, testing using NUnit3
Brief pseudocode example:
//we have one connector for each connected client
class connector{
//if the echoReceived timer is not reseted on time it will complain
Timer echoReceived = new Timer(200ms);
//Another timer for sending beats
Timer heartbeatSender = new Timer (1000ms);
OnClientConnected(Client)
{
echoReceived.elapsed += () => { ShowError("Client did not reply") };
heartbeatSender.elapsed += () => {
Send(client, new Message(Heartbeat));
echoReceived.Enabled = true;
});
heartbeatSemder.isEnabled = true;
}
OnNewMessageFromClient(Client, message)
{
if(message is echoedHeartBeat)
{
echoReceived.Enabled= false;
echoReceived.Reset();
}
}
}
On the client side
class client
{
Timer ServerDeadTimeOut = new Timer (1000ms);
OnStart()
{
serverDeadTimeOut.Elapsed += () => { ShowError("Server is dead"); };
serverDeadTimeOut.isEnabled = true;
}
OnNewMessageFromServer(message)
{
if(message is HeartBeatMessage)
{
serverDeadTimeOut.Reset();
Send(new HeartBeatEchoMessage);
}
}
}