简体   繁体   English

如何测试套接字异常处理代码?

[英]How do I test my socket exception handling code?

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? 如果服务器一直在成功侦听,我该如何测试代码的SocketException

Do not test against the live network. 不要对实时网络进行测试。 Mock the socket and test against a mock that throws a SocketException . 模拟套接字并针对抛出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. 就像有一个无效的配置设置,它不会让它连接用于你的单元测试代码。

拔下网络电缆或关闭无线网络(假设您正在测试远程服务器)。

Manually throw a SocketException from inside your try block. 从try块中手动抛出SocketException

Like 喜欢

throw new SocketException("Testing");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM