2008-10-24 33 views
4

我在RhinoMocks中使用模擬對象來表示調用MessageQueue.GetPublicQueues的類。我想模擬消息隊列在工作組模式下運行時引發的異常(這是一個MessageQueueException),以確保我能夠正確捕獲異常是否可以拋出MessageQueueException?

MessageQueueException沒有公共構造函數,只有標準的受保護的構造函數用於異常。有沒有從模擬對象/ Expect.Call語句中引發此異常的適當方法?

回答

5

反射會破壞可訪問性規則。您的保修無效,.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; 
+0

工程請客:-) – BlackWasp 2008-10-25 09:20:06

3

你可以通過嘗試創建一個無效的隊列。也許更安全的則正在舉行的框架的變化俘虜(通過使用私有/保護的構造函數):

MessageQueue mq = MessageQueue.Create("\\invalid"); 
相關問題