Has anyone successfully mocked the Socket class in .NET?(有没有人成功地模拟过 .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 类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:有没有人成功地模拟过 .NET 中的 Socket 类?
基础教程推荐
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
