【问题标题】:Is it possible to throw a MessageQueueException?是否可以抛出 MessageQueueException?
【发布时间】:2008-10-24 23:10:46
【问题描述】:

我在 RhinoMocks 中使用一个模拟对象来表示一个调用 MessageQueue.GetPublicQueues 的类。我想模拟消息队列在工作组模式下运行时抛出的异常,即MessageQueueException,以确保我正确捕获异常

MessageQueueException 没有公共构造函数,只有标准的受保护异常构造函数。有没有合适的方法从模拟对象/Expect.Call 语句中抛出这个异常?

【问题讨论】:

    标签: c# .net exception tdd rhino-mocks


    【解决方案1】:

    反射可以打破可访问性规则。您使保修失效,.NET 更新很容易破坏您的代码。试试这个:

    using System.Reflection;
    using System.Messaging;
    ...
            Type t = typeof(MessageQueueException);
            ConstructorInfo ci = t.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, 
              null, new Type[] { typeof(int) }, null);
            MessageQueueException ex = (MessageQueueException)ci.Invoke(new object[] { 911 });
            throw ex;
    

    【讨论】:

    • 现在记住你这样做了,因为每次他们修补或更新框架时,这可能是一个重大变化......以前在 prod 系统中存在。糟透了。为什么你需要抛出这个异常?难道你不能也只是用 MessageQueue 做一些无效的事情来得到它吗?!
    【解决方案2】:

    您可以通过尝试创建无效队列来导致此问题。可能比被框架更改俘虏更安全(通过使用私有/受保护的构造函数):

    MessageQueue mq = MessageQueue.Create("\\invalid");
    

    【讨论】:

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