【问题标题】:How-To Mock MSMQ MessageQueue如何模拟 MSMQ 消息队列
【发布时间】:2010-12-10 07:17:23
【问题描述】:

我想对使用 MSMQ 的应用程序进行单元测试,但我没有办法模拟 MessageQueue 对象。

        var queuePath = @".\Private$\MyQueue";
        MessageQueue queue = null;
        if (MessageQueue.Exists(queuePath))
        {
            queue = new MessageQueue(queuePath);
        }
        else
        {
            queue = MessageQueue.Create(queuePath);
        }

我将 Moq 与 xUnit 一起使用。

【问题讨论】:

    标签: unit-testing msmq moq


    【解决方案1】:

    所以这里的基本问题是你对 MessageQueue 对象有一个硬依赖。一般遇到这种情况,我会先创建一个接口,比如IQueue,然后再为MessageQueue创建一个IQueue的实现。

    然后您可以使用 Moq 注入 IQueue 依赖项并测试您的类是否按预期运行。

    类似这样的:

    public interface IQueue
    {
         bool Exists(string path);
         MessageQueue Create(string path);
    }
    

    实现是这样的:

    public MessageQueueImplementation : IQueue
    {
        public bool Exists(string path)
        {
             return MessageQueue.Exists(path);
        }
    
        public MessageQueue Create(string path)
        {
             return MessageQueue.Create(path);
        }
    }
    

    然后对于依赖于 MessageQueue 的类,如下所示:

    public class DependentOnQueue
    {
        private IQueue queue;
        //inject dependency
        public DependentOnQueue(IQueue queue)
        {
            this.queue = queue;
        }
    
        public MessageQueue CreateQueue(string path)
        {
             //implement method that you want to test here
        }
    }
    

    现在您可以使用 moq 将 IQueue 对象注入到依赖于 MessageQueue 对象的此类中并测试功能。

    【讨论】:

    • +1。这也是最后 10 个“我如何模拟 [Class X]?”的公认答案。问题。我不知道为什么人们不接受这个。
    • 除了Create 方法(顺便说一句,它应该是静态的)之外,包装类似乎可以作为解决方案工作,因为该方法的签名返回一个System.Messaging.MessageQueue,它没有实现IQueue。有没有人想出一个解决方法?
    • @Cupcake 您可以使用返回 IQueue 的 Create 方法创建 IQueueManager 或类似的东西。使用 IQueueManager 的 MsmqManager 实现,该实现依次调用静态 MessageQueue.Create 并返回结果的 MessageQueueImplementation。
    猜你喜欢
    • 1970-01-01
    • 2014-12-22
    • 2018-02-20
    • 2011-04-27
    • 2011-07-31
    • 2015-01-24
    • 2012-12-28
    • 2017-06-29
    • 2012-03-27
    相关资源
    最近更新 更多