开发者

How do I test my socket exception handling code?

I have the following code:

try
{
  mai开发者_StackOverflownSocket = 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?


Do not test against the live network. Mock the socket and test against a mock that throws a SocketException.


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.


Unplug your network cable or shut off your wireless (assuming you're testing against a remote server).


Manually throw a SocketException from inside your try block.

Like

throw new SocketException("Testing");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜