是否可能对异步套接字编程进行单元测试(使用c#)?请提供一些样本单元测试代码。
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框架。
[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();
}
APM
不再是异步TCP的推荐模式。现在建议使用async/await
(https://github.com/dotnet/core/issues/4828#issuecomment-643694377)。微软文档已经过时,基于旧的APM模式。我已经得到了答案。赏金已经没有用处了。 - tinonetic