Elmah FromCurrentContext error logging aborts during unit testing

When writing unit tests using Moq anytime I call Elmah.ErrorSignal.FromCurrentContext , it fails with a null reference exception. I can mock ControllerContext , and I would just like to use an error log command like this.

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

but unfortunately ControllerContext.HttpContext is of type HttpContextBase and will not work with this error logging method.

Is there a better way to directly call the Elmah error log? Unfortunately, the Application.HttpContext object cannot be mocked (below the example) or which will also serve the purpose.

Mock Application and 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); 

Error generated:

Incorrect setting for a non-virtual (redefined in VB) member

+8
unit-testing moq asp.net-mvc-3 elmah
source share
2 answers

One thing you can do to register an error in Elmah differently is to use:

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

Although this will not result in error logging from unit test, it will at least skip logging in unit test altogether and still log the error under normal circumstances.

+7
source share

Although you cannot make fun of HttpContext, you can configure HttpContext.Current in your test.

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

I am not sure which parts of the context are used by Elmah.

Third Party Editing:
ELMAH also requires 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() 

otherwise it throws an exception because the application name is NULL.

Further editing:
Here is the final code in 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()}; 
+13
source share

All Articles