問題描述
我們使用 ELMAH 來處理我們的 ASP.Net MVC c# 應用程序中的錯誤,并且在我們捕獲的異常中,我們正在做這樣的事情:
We're using ELMAH for handling errors in our ASP.Net MVC c# application and in our caught exceptions, we're doing something like this:
ErrorSignal.FromCurrentContext().Raise(exception);
但是當我嘗試對捕獲的異常進行單元測試時,我收到以下消息:
but when I try to unit test the caught exceptions, I get this message:
System.ArgumentNullException: Value cannot be null.
Parameter name: context
如何模擬 FromCurrentContext() 調用?有什么我應該做的嗎?
How can I mock the FromCurrentContext() call? Is there something else I should be doing instead?
僅供參考...我們目前正在使用 Moq 和 RhinoMocks.
FYI... We're currently using Moq and RhinoMocks.
謝謝!
推薦答案
由于 FromCurrentContext()
方法是一個靜態方法,你不能簡單地模擬對它的調用.你還有另外兩個選擇.
Since the FromCurrentContext()
method is a static method you can't simply mock the call to it. You do have two other options.
由于
FromCurrentContext()
在內部調用HttpContext.Current
您可以在其中推送一個假上下文.例如:
Since
FromCurrentContext()
internally makes a call toHttpContext.Current
you can push a fake context in that. For example:
SimpleWorkerRequest request = new SimpleWorkerRequest(
"/blah", @"c:inetpubwwwrootlah", "blah.html", null, new StringWriter());
HttpContext.Current= new HttpContext(request);
有了這個,它不應該再拋出異常,因為 HttpContext.Current
不為空.
With this it should not throw the exception anymore since HttpContext.Current
is not null.
圍繞對 Raise 的調用創建一個封裝類,然后模擬出封裝類.
Create a wrapper class around the call to Raise and just mock out the wrapper class.
public class ErrorSignaler {
public virtual void SignalFromCurrentContext(Exception e) {
if (HttpContext.Current != null)
Elmah.ErrorSignal.FromCurrentContext().Raise(e);
}
}
這篇關于如何模擬 Elmah 的 ErrorSignal 例程?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!