2012-05-18 78 views
8

使用Moq隨時編寫單元測試時,我會調用Elmah.ErrorSignal.FromCurrentContext,它會失敗並返回空引用異常。我可以嘲笑ControllerContext,我想只用一個錯誤日誌命令,這樣的..Elmah錯誤日誌記錄FromCurrentContext在單元測試時中斷

Elmah.ErrorSignal.FromContext(ControllerContext.HttpContext).Raise(e); 

可惜ControllerContext.HttpContextHttpContextBase型的,不會與此錯誤測井方法工作。

有沒有更好的方法直接調用Elmah錯誤日誌記錄?不幸的是,Application.HttpContext對象不能被模擬(下面的例子),或者這也可以達到目的。

Application模擬和Application.HttpContext

ctrlCtx.SetupGet(x => x.HttpContext.ApplicationInstance) 
      .Returns(new Mock<HttpApplication>().Object); 
ctrlCtx.SetupGet(x => x.HttpContext.ApplicationInstance.Context) 
      .Returns(new Mock<HttpContext>().Object); 

錯誤製作人:

在非虛擬(在VB重寫)構件

無效設置

+0

相關:[我如何模擬Elmah的ErrorSignal例程?](http://stackoverflow.com/questions/1019833/how-can-i-mock-elmahs-errorsignal-routine) – 2014-12-17 10:14:58

回答

7

一件事是使用:

Elmah.ErrorLog.GetDefault(null).Log(new Elmah.Error(e)); 

雖然這不會在單元測試中記錄錯誤,它至少會在單元測試中完全跳過日誌記錄,並且在正常情況下仍會記錄錯誤。

13

雖然無法嘲笑HttpContext的,可以在你的測試中設置HttpContext.Current。

var req = new HttpRequest(string.Empty, "https://www.domain.tld", null); 
var res = new HttpResponse(null); 
HttpContext.Current = new HttpContext(req, res); 

我不確定Elmah使用上下文的哪些部分。

第三方編輯:
ELMAH還需要System.Web.HttpContext.Current.ApplicationInstance

Dim req As System.Web.HttpRequest = New System.Web.HttpRequest(String.Empty, "https://www.domain.tld", Nothing) 
Dim res As System.Web.HttpResponse = New System.Web.HttpResponse(Nothing) 
System.Web.HttpContext.Current = New System.Web.HttpContext(req, res) 

System.Web.HttpContext.Current.ApplicationInstance = New System.Web.HttpApplication() 

否則它拋出一個異常,因爲應用程序名稱爲NULL。

進一步編輯:
這是在C#中的最終代碼:

你可以做登錄不同的ELMAH錯誤
var req = new HttpRequest(string.Empty, "https://www.domain.tld", null); 
var res = new HttpResponse(null); 
HttpContext.Current = new HttpContext(req, res) 
    {ApplicationInstance = new HttpApplication()};