Reputation: 8342
I have the following code:
try
{
mainSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, serverPort);
mainSocket.Bind(ipEndPoint);
mainSocket.Listen(MAX_CONNECTIONS);
mainSocket.BeginAccept(new AsyncCallback(serverEndAccept), mainSocket);
OnNetworkEvents eventArgs =
new OnNetworkEvents(true, "Listening for Connection");
OnUpdateNetworkStatusMessage(this, eventArgs);
}
catch (SocketException e)
{
// add code here
}
catch (ObjectDisposedException e)
{
// add code here
}
How do I test the code's SocketException
given the server is listening successfully all of the time?
Upvotes: 3
Views: 3909
Reputation: 234594
Do not test against the live network. Mock the socket and test against a mock that throws a SocketException
.
Upvotes: 8
Reputation: 50235
Unplug your network cable or shut off your wireless (assuming you're testing against a remote server).
Upvotes: 3
Reputation: 1349
you could add something like this for testing:
#if (UNITTEST)
throw new SocketException();
#endif
Then in your unit test compile just define that variable.
Otherwise do something to force an exception. Like have an invalid config setting that won't let it connect for use with your unit test code.
Upvotes: 3
Reputation: 83290
Manually throw a SocketException
from inside your try block.
Like
throw new SocketException("Testing");
Upvotes: 2