我正在尝试在 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 类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!