Asp.net-Mvc-3

Elmah 錯誤記錄 FromCurrentContext 在單元測試時中斷

  • September 1, 2016

任何時候使用 Moq 編寫單元測試時,我呼叫Elmah.ErrorSignal.FromCurrentContext它都會失敗,並出現空引用異常。我能夠模擬ControllerContext並且我只想使用這樣的錯誤日誌命令..

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

但不幸的ControllerContext.HttpContext是,它是類型HttpContextBase,不適用於這種錯誤記錄方法。

有沒有更好的方法來直接呼叫 Elmah 錯誤記錄?不幸的是,該對Application.HttpContext像不能被模擬(下面的例子)或者也可以達到目的。

模擬ApplicationApplication.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 中可覆蓋)成員上的設置無效

在 Elmah 中以不同方式記錄錯誤的一件事是使用:

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

儘管這不會從單元測試中記錄錯誤,但它至少會在單元測試中完全跳過記錄,並且在正常情況下仍會記錄錯誤。

雖然您不能模擬 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 使用了上下文的哪些部分。

第 3 方編輯:

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# 中的最終程式碼:

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()};

引用自:https://stackoverflow.com/questions/10657961