views:

215

answers:

2

I am using a mock object in RhinoMocks to represent a class that makes calls to MessageQueue.GetPublicQueues. I want to simulate the exception thrown when message queueing is operating in workgroup mode, which is a MessageQueueException, to ensure that I am catching the exception correctly

The MessageQueueException has no public constructor, only the standard protected constructor for an exception. Is there an appropriate way to throw this exception from the mock object / Expect.Call statement?

+2  A: 

Reflection can break the accessibility rulez. Try this:

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;
Hans Passant
Works a treat :-)
BlackWasp
Now remember you did that because everytime they patch or update the framework, it can be a breaking change... been there in a prod system before. it sucks.Why do you need to throw THIS exception? Could you not also just do something invalid with a MessageQueue to get it?!
TheSoftwareJedi
A: 

You can cause this by trying to create an invalid queue. Probably safer then being held captive by framework changes (through using private/protected constructors):

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