我们使用 ELMAH 来处理我们的 ASP.Net MVC c# 应用程序中的错误和我们捕获的异常,我们正在做这样的事情:
ErrorSignal.FromCurrentContext().Raise(exception);
但是当我尝试对捕获的异常进行单元测试时,我收到了这条消息:
System.ArgumentNullException: Value cannot be null.
Parameter name: context
如何模拟 FromCurrentContext() 调用? 有什么我应该做的吗?
仅供引用...我们目前正在使用 Moq 和 RhinoMocks。
谢谢!
最佳答案
由于 FromCurrentContext()
方法是静态方法,您不能简单地模拟对它的调用。您还有其他两个选择。
由于
FromCurrentContext()
在内部调用了HttpContext.Current
,您可以在其中推送一个假上下文。例如:SimpleWorkerRequest request = new SimpleWorkerRequest( "/blah", @"c:\inetpub\wwwroot\blah", "blah.html", null, new StringWriter()); HttpContext.Current= new HttpContext(request);
由于
HttpContext.Current
不为空,因此它不应再抛出异常。围绕对 Raise 的调用创建一个包装类,然后模拟包装类。
public class ErrorSignaler { public virtual void SignalFromCurrentContext(Exception e) { if (HttpContext.Current != null) Elmah.ErrorSignal.FromCurrentContext().Raise(e); } }
关于c# - 我如何模拟 Elmah 的 ErrorSignal 例程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1019833/