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 类?


基础教程推荐
- 如果条件可以为空 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 将数据集转换为列表 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01