I've been passed a bit of code that needs to have some unit tests added to it.
The class in question is a Socket server that listens asynchronously for a handshake from any clients attempting to connect. If the handshake is successful then the client is enrolled and everyone is happy. Obviously there's more to it than that but that should be enough to get started with.
The outline of the class goes:
public class MyServer
{
private Socket _Server;
private List<MyClient> _clients;
public int ClientCount
{
_clients.Count;
}
public void StartListening()
{
_Server = new Socket(...)
... // Configure the socket
_Server.BeginAccept(new AsyncCallback(CheckHandshake), null);
}
private void CheckHandshake(IAsyncResult result)
{
... // Read data from potential Client
... // Test handshake
if(HandShakeOK)
{
var newClient = MyClient();
... // Configure client from received data
_clients.Add(newClient);
}
}
}
As a starting place I fist want to check that the number of enrolled clients (ClientCount) increases by 1 when a client is successfully enrolled. As it stands the code doesn't make unit testing very easy so I started off by introducing an ISocket interface and SocketAdapter wrapper to help with mocking. I then modified the StartListening() method so that a Mock could be injected, like so:
public void StartListening(ISocket server)
{
_Server = server;
_Server.BeginAccept(new AsyncCallback(CheckHandshake), null);
}
This is where I'm getting stuck though. I can spin up a mock, I can get the mock into the class and I know what I want to check but how should I be configuring the Mock to stimulate the increment I'm checking for. I don't want to be assuming anything about the internal state of the MyServer class if possible and I'm happy to refactor the existing code if it'll help to make the testing easier.
Aucun commentaire:
Enregistrer un commentaire