有没有人成功地嘲笑.NET中的Socket类? [英] Has anyone successfully mocked the Socket class in .NET?
问题描述
我正在尝试模拟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类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!