简体   繁体   English

使用Moles模拟System.Net.Sockets

[英]Using Moles to mock System.Net.Sockets

I'm trying to use Moles to mock the Socket class in System.Net.Sockets. 我正在尝试使用Moles来模拟System.Net.Sockets中的Socket类。 I have successfully generated the .moles file and building it did add a System.Net.Moles assembly to my references but It dose not generate the MSocket class. 我已经成功生成了.moles文件,并对其进行了构建,并确实向我的引用中添加了System.Net.Moles程序集,但它没有生成MSocket类。 In fact only the MIPEndPointCollection class is generated. 实际上,仅生成MIPEndPointCollection类。

Here is a sample class that uses System.Net.Sockets.Socket: 这是使用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;
        }
    }
}

A dumy test class: 杜比测试班:

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);
        }
    }
}

And my .moles file: 和我的.moles文件:

<Moles xmlns="http://schemas.microsoft.com/moles/2010/">
  <Assembly Name="System.Net" />
</Moles>

Can someone pleas point out what is wrong with this and what to do to make it work. 有人可以指出这有什么问题以及如何使它起作用。 I know that there are other ways to mock out the Socket class for example with a wrapper class that implements my own interface but I'm only interested in doing this using Moles. 我知道还有其他方法可以模拟Socket类,例如使用实现我自己的接口的包装器类,但是我只对使用Moles做到这一点感兴趣。

--Thanks Daniel -感谢Daniel

In my experience, Moling the System assembly is quirky. 以我的经验,对系统组件进行Moling是古怪的。 Try this for the second line of your .moles file: 在您的.moles文件的第二行尝试以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM