views:

152

answers:

4

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?

+2  A: 

Manually throw a SocketException from inside your try block.

Like

throw new SocketException("Testing");
danben
this works except "testing" has to be a number.thanks.
iEisenhower
@ikurtz: just remember if you add this to your code vs using a conditional for testing that you have to remove it and readd it whenever you want to test again. Where if you can modify a config file or use conditional compilation you can test whenever you need to and test all code paths.
Joshua Cauble
+3  A: 

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.

Joshua Cauble
this is a cool approach except im a beginner and although i understand the concept, i will have study the net to actually understand it.
iEisenhower
+3  A: 

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

Austin Salonen
+4  A: 

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

Martinho Fernandes