c# - 我如何模拟 Elmah 的 ErrorSignal 例程?

标签 c# asp.net-mvc mocking elmah

我们使用 ELMAH 来处理我们的 ASP.Net MVC c# 应用程序中的错误和我们捕获的异常,我们正在做这样的事情:

ErrorSignal.FromCurrentContext().Raise(exception);

但是当我尝试对捕获的异常进行单元测试时,我收到了这条消息:

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);
    

    由于 HttpContext.Current 不为空,因此它不应再抛出异常。

  2. 围绕对 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/

相关文章:

angularjs - AngularJS 的 Karma/Jasmine 中的模拟模块依赖关系

c# - 如何强制使用 void 方法从 Stub 对象返回 Void?

c# - EF6 代码优先 "Foreign Key Multiplicity is not valid in Role"

c# - 在没有类型拆箱的情况下调用具有特定参数的方法

c# - Google Vision API指定JSON文件

c# - 无参数 Controller 构造函数 Autofac

asp.net-mvc - RazorEngine 和解析物理 View 文件总是导致异常

asp.net-mvc - www.example.com 不起作用,但 example.com 起作用

java - NullPointerException ftp.stop() FakeFtpServer/mockFTPServer

c# - 具有意外行为的通用方法参数