【问题标题】:Using Moles to mock System.Net.Sockets使用 Moles 模拟 System.Net.Sockets
【发布时间】:2023-04-08 23:39:01
【问题描述】:

我正在尝试使用 Moles 来模拟 System.Net.Sockets 中的 Socket 类。我已成功生成 .moles 文件并构建它确实将 System.Net.Moles 程序集添加到我的引用中,但它不会生成 MSocket 类。实际上只生成了 MIPEndPointCollection 类。

这是一个使用 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;
        }
    }
}

一个虚拟测试类:

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 进行此操作感兴趣。

--谢谢丹尼尔

【问题讨论】:

  • “我知道还有其他方法可以模拟 Socket 类,例如使用实现我自己的接口的包装类,但我只对使用 Moles 进行此操作感兴趣。” - 恕我直言,唯一的正当理由是,如果您正在处理相对较大的遗留代码库。如果不是这种情况,请使用包装器+接口。
  • @TrueWill 这似乎与我最近看到的一篇博文一致。我喜欢你关于外部性的精简、精简包装器的概念,以使你的代码尽可能地解耦。即使使用像 XDocument API 这样简单的东西,我也已经对此进行了试验,并且通常发现它是一种可靠的方法。

标签: c# .net unit-testing mocking moles


【解决方案1】:

根据我的经验,Moling the System 组件很奇怪。在 .moles 文件的第二行试试这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多