2012-02-20 16 views
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丹尼爾

+0

「我知道有其他的方法來模擬出例如Socket類與實現我自己的接口的包裝類,但我只關心用痣做這個。「 - 恕我直言,**只有**有效的原因是,如果你正在處理一個相對較大的遺留代碼庫。如果情況並非如此,請使用wrapper +界面。 – TrueWill 2012-02-20 19:32:23

+1

@TrueWill這似乎與我最近看到的你的博客文章一致。我喜歡你的外觀簡潔精簡包裝的概念,以保持代碼儘可能分離。我已經嘗試過使用XDocument API這樣簡單的東西,並且通常認爲它是一個可靠的方法。 – 2012-02-20 22:28:13

回答

1

以我的經驗,秣陵系統組件是古怪。試試這個你.moles文件的第二行:

<Assembly Name="System" ReflectionOnly="true" />