如何对网络连接进行单元测试?
我想对下面的代码进行单元测试。我一直在使用 MSTest,并尝试学习 Microsoft Moles 和 < a href="http://ayende.com/blog/tags/rhino-mocks" rel="nofollow">RhinoMocks。但我无法让他们都帮我。我知道我可以彻底更改代码以使用使其更易于测试的接口,但这需要我编写封装 TcpClient、NetworkStream、StreamWriter 和 StreamReader 的接口和实现。
我已经为此编写了集成测试,我想精通摩尔的人可以很容易地为此进行单元测试,而无需更改代码。
using (TcpClient tcpClient = new TcpClient(hostName, port))
using (NetworkStream stream = tcpClient.GetStream())
using (StreamWriter writer = new StreamWriter(stream))
using (StreamReader reader = new StreamReader(stream))
{
writer.AutoFlush = true;
writer.Write(message);
return reader.ReadLine();
}
I want to unit test the code below. I've been working with MSTest and I tried to learn Microsoft Moles and RhinoMocks. But I couldn't make neither of them help me. I know I can change the code drastically to use interfaces that make it more testable, but it would require me to code interfaces and implementations that encapsulate TcpClient, NetworkStream, StreamWriter and StreamReader.
I've already written integration test for this and I guess that someone proficient with moles can do unit tests for this quite easily without changing the code.
using (TcpClient tcpClient = new TcpClient(hostName, port))
using (NetworkStream stream = tcpClient.GetStream())
using (StreamWriter writer = new StreamWriter(stream))
using (StreamReader reader = new StreamReader(stream))
{
writer.AutoFlush = true;
writer.Write(message);
return reader.ReadLine();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
保持简单。
抽象掉网络层。我通常使用一个名为
INetworkChannel
的接口,它看起来像这样:它可以轻松测试所有内容,并且您可以创建使用
SslStream
SecureNetworkChannel 类code> 或FastNetworkChannel
使用新的异步方法。使用什么流或是否使用
TcpClient
还是Socket
等详细信息对于应用程序的其余部分来说应该不重要。编辑
测试
INetworkingChannel
实现也很容易,因为您现在有了一个职责非常明确的类。我确实创建了与我的实现的连接来测试它们。让TcpListener
监听端口0
,让操作系统分配一个空闲端口。我只是确保它正确处理发送和接收,并且在连接关闭/断开时进行正确的清理。
Keep it simple.
Abstract away the network layer. I usually use an interface called something like
INetworkChannel
that looks something like this:It makes it easy to test everything and you could create
SecureNetworkChannel
class which usesSslStream
orFastNetworkChannel
which uses the new Async methods.The details like what stream is used or if you use
TcpClient
orSocket
should not matter to the rest of the application.Edit
Testing the
INetworkingChannel
implementation is easy too since you now got a class with a very clear responsibility. I do create a connection to my implementations to test them. Let theTcpListener
listen on port0
to let the OS assign a free port.I just make sure that it handle sends and receives properly and that it do proper clean up when a connection is closed/broken.