我如何模仿Elmah的ErrorSignal例程?

我们使用ELMAH处理ASP.Net MVC c#应用程序中的错误,在我们捕获的exception中,我们正在执行以下操作:

ErrorSignal.FromCurrentContext().Raise(exception); 

但是当我尝试对捕获的exception进行unit testing时,我收到此消息:

 System.ArgumentNullException: Value cannot be null. Parameter name: context 

如何模拟FromCurrentContext()调用? 我还应该做些什么呢?

仅供参考……我们目前正在使用Moq和RhinoMocks。

谢谢!

由于FromCurrentContext()方法是静态方法,因此您不能简单地模拟对它的调用。 你还有其他两个选择。

  1. 由于FromCurrentContext()内部调用HttpContext.Current您可以在其中推送伪上下文。 例如:

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

    有了它,它不应再抛出exception,因为HttpContext.Current不为null。

  2. 围绕调用Raise创建一个包装类,并模拟包装类。

     public class ErrorSignaler { public virtual void SignalFromCurrentContext(Exception e) { if (HttpContext.Current != null) Elmah.ErrorSignal.FromCurrentContext().Raise(e); } }