C#Asyn.套接字编程 [英] C# Asyn. Socket Programming

查看:76
本文介绍了C#Asyn.套接字编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以对Asyn进行单元测试.套接字编程(使用C#)?提供一些样本单元测试代码.

Is it possible to unit test the Asyn. socket programming (using c#)? Provide some sample unit test code.

推荐答案

我假设您正在测试自己的一些使用.NET流的类;我们称之为 MessageSender .请注意,没有理由对.NET流本身进行单元测试,这是Microsoft的工作.您不应仅对自己的.NET Framework代码进行单元测试.

I assume you are testing some class of your own that uses .NET streams; let's call it MessageSender. Note that there is no reason to unit test the .NET streams themselves, that's Microsoft's job. You should not unit test .NET framework code, just your own.

首先,请确保您注入 MessageSender 使用的流.不要在类内部创建它,而应将其作为属性值或构造函数参数接受.例如:

First, make sure that you inject the stream used by MessageSender. Don't create it inside the class but accept it as a property value or constructor argument. For example:

public sealed class MessageSender
{
   private readonly Stream stream;

   public MessageSender(Stream stream)
   {
      if (stream == null)
         throw new ArgumentNullException("stream");
      this.stream = stream;
   }

   public IAsyncResult BeginSendHello(AsyncCallback callback, object state)
   {
      byte[] message = new byte[] {0x01, 0x02, 0x03};
      return this.stream.BeginWrite(
         message, 0, message.Length, callback, state);
   }

   public void EndSendHello(IAsyncResult asyncResult)
   {
      this.stream.EndWrite(asyncResult);
   }
}

现在是一个示例测试:您可以测试 BeginSendHello 在流上调用 BeginWrite ,并发送正确的字节.我们将模拟流,并建立一个期望来验证这一点.在此示例中,我使用的是 RhinoMocks 框架.

Now an example test: you could test that BeginSendHello invokes BeginWrite on the stream, and sends the correct bytes. We'll mock the stream and set up an expectation to verify this. I'm using the RhinoMocks framework in this example.

[Test]
public void BeginSendHelloInvokesBeginWriteWithCorrectBytes()
{
   var mocks = new MockRepository();
   var stream = mocks.StrictMock<Stream>();
   Expect.Call(stream.BeginWrite(
      new byte[] {0x01, 0x02, 0x03}, 0, 3, null, null));
   mocks.ReplayAll();

   var messageSender = new MessageSender(stream);
   messageSender.BeginSendHello(null, null);

   mocks.VerifyAll();
}

这篇关于C#Asyn.套接字编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆