17

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

How can I mock the FromCurrentContext() call? Is there something else I should be doing instead?

FYI... We're currently using Moq and RhinoMocks.

Thanks!

tereško
  • 58,060
  • 25
  • 98
  • 150
Chris Conway
  • 16,269
  • 23
  • 96
  • 113

1 Answers1

34

Since the FromCurrentContext() method is a static method you can't simply mock the call to it. You do have two other options.

  1. Since FromCurrentContext() internally makes a call to HttpContext.Current you can push a fake context in that. For example:

    SimpleWorkerRequest request = new SimpleWorkerRequest(
        "/blah", @"c:\inetpub\wwwroot\blah", "blah.html", null, new StringWriter());
    
    HttpContext.Current= new HttpContext(request);
    

    With this it should not throw the exception anymore since HttpContext.Current is not null.

  2. 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);
        } 
    }
    
Darko
  • 38,310
  • 15
  • 80
  • 107
Matthew Manela
  • 16,572
  • 3
  • 64
  • 66
  • 12
    This is an older question so maybe things have changed, but for Elmah 1.1, I had to also initialize the HttpContext.Current.ApplicationInstance to a new HttpApplication() for this to work. Thanks! – PatrickSteele Aug 25 '11 at 13:05
  • 1
    Another option is this: 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()
    – Stefan Steiger Oct 10 '12 at 14:30