Search code examples
asp.net-mvc-3unit-testingmoqelmah

Elmah error logging FromCurrentContext breaks when unit testing


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

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

but unfortunately the ControllerContext.HttpContext is of type HttpContextBase and won't work with this error logging method.

Is there a better way to call the Elmah error logging directly? Unfortunately the Application.HttpContext object cannot be mocked (below example) or that would 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 Produced:

Invalid setup on a non-virtual (overridable in VB) member


Solution

  • One thing you can do to log the error differently in Elmah is to use:

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

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