問題描述
我正在嘗試在 C# 中模擬 System.net.Sockets.Socket 類 - 我嘗試使用 NUnit 模擬,但它無法模擬具體類.我也嘗試使用 Rhino Mocks,但它似乎使用了該類的真實(shí)版本,因?yàn)樗谡{(diào)用 Send(byte[]) 時(shí)拋出了 SocketException.是否有人使用任何模擬框架成功創(chuàng)建并使用了 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?
推薦答案
每當(dāng)我遇到 Moq 的這類問題時(shí),我最終都會(huì)創(chuàng)建一個(gè)接口來抽象出我無法模擬的東西.
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.
因此,在您的實(shí)例中,您可能有一個(gè)實(shí)現(xiàn) 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.
在你的實(shí)際代碼中,你會(huì)有一個(gè)這樣的類
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.
這篇關(guān)于有沒有人成功地模擬過 .NET 中的 Socket 類?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!