有没有人成功地模拟过 .NET 中的 Socket 类?

Has anyone successfully mocked the Socket class in .NET?(有没有人成功地模拟过 .NET 中的 Socket 类?)
本文介绍了有没有人成功地模拟过 .NET 中的 Socket 类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试在 C# 中模拟 System.net.Sockets.Socket 类 - 我尝试使用 NUnit 模拟,但它无法模拟具体类.我也尝试使用 Rhino Mocks,但它似乎使用了该类的真实版本,因为它在调用 Send(byte[]) 时抛出了 SocketException.是否有人使用任何模拟框架成功创建并使用了 Socket 模拟?

I'm trying to mock out the System.net.Sockets.Socket class in C# - I tried using NUnit mocks but it can't mock concrete classes. I also tried using Rhino Mocks but it seemed to use a real version of the class because it threw a SocketException when Send(byte[]) was called. Has anyone successfully created and used a Socket mock using any mocking framework?

推荐答案

每当我遇到 Moq 的这类问题时,我最终都会创建一个接口来抽象出我无法模拟的东西.

Whenever I run into these kinds of problems with Moq I end up creating an interface to abstract away the thing I can't mock.

因此,在您的实例中,您可能有一个实现 Send 方法的 ISocket 接口.然后让你的模拟框架模拟它.

So in your instance you might have an ISocket interface that implements the Send method. Then have your mocking framework mock that instead.

在你的实际代码中,你会有一个这样的类

In your actual code, you'd have a class like this

public class MySocket : ISocket
{
  System.Net.Sockets.Socket _socket;

  public void MySocket(System.Net.Sockets.Socket theSocket)
  {
    _socket = theSocket;
  }

  public virtual void Send(byte[] stuffToSend)
  {
    _socket.Send(stuffToSend);
  }

}

不确定这是否满足您的需求,但这是一种选择.

Not sure if that meets your needs, but it's an option.

这篇关于有没有人成功地模拟过 .NET 中的 Socket 类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)
How to store delegates in a List(如何将代表存储在列表中)
How delegates work (in the background)?(代表如何工作(在后台)?)
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)