1
我试图用莫尔模拟System.Net.Sockets中的Socket类。我已经成功地生成了.moles文件,并且构建它将System.Net.Moles组件添加到了我的引用中,但它不会生成MSocket类。实际上只生成了MIPEndPointCollection类。使用鼹鼠来模拟System.Net.Sockets
下面是一个使用System.Net.Sockets.Socket样品等级:
using System.Text;
using System.Net.Sockets;
namespace MyProject
{
public static class Communicator
{
public static int Send(string messages)
{
byte[] bytes = Encoding.ASCII.GetBytes(messages);
int bytesSent = 0;
using (Socket socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp))
{
socket.Connect("localhost", 1234);
bytesSent = socket.Send(bytes);
}
return bytesSent;
}
}
}
一个dumy测试类:
using MyProject;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Net.Moles;
using Microsoft.Moles.Framework;
[assembly: MoledType(typeof(System.Net.Sockets.Socket))]
namespace MyProjectTest
{
[TestClass()]
public class CommunicatorTest
{
private TestContext testContextInstance;
public TestContext TestContext
{
get { return testContextInstance; }
set { testContextInstance = value; }
}
[TestMethod()]
[HostType("Moles")]
public void SendTest()
{
//dose not exist in the System.Net.Moles namespace:
//MSocket.Send = deligate(){ return 0; };
int bytesSent = Communicator.Send("Test Message");
Assert.AreEqual(0, bytesSent);
}
}
}
而且我.moles文件:
<Moles xmlns="http://schemas.microsoft.com/moles/2010/">
<Assembly Name="System.Net" />
</Moles>
有人可以请求指出这有什么问题以及如何使其工作。我知道还有其他方法可以模拟出Socket类,例如使用实现我自己的接口的包装类,但是我只对使用Moles做这个感兴趣。
--Thanks丹尼尔
“我知道有其他的方法来模拟出例如Socket类与实现我自己的接口的包装类,但我只关心用痣做这个。“ - 恕我直言,**只有**有效的原因是,如果你正在处理一个相对较大的遗留代码库。如果情况并非如此,请使用wrapper +界面。 – TrueWill 2012-02-20 19:32:23
@TrueWill这似乎与我最近看到的你的博客文章一致。我喜欢你的外观简洁精简包装的概念,以保持代码尽可能分离。我已经尝试过使用XDocument API这样简单的东西,并且通常认为它是一个可靠的方法。 – 2012-02-20 22:28:13