如何模拟 Elmah 的 ErrorSignal 例程?

How can I mock Elmah#39;s ErrorSignal routine?(如何模拟 Elmah 的 ErrorSignal 例程?)
本文介绍了如何模拟 Elmah 的 ErrorSignal 例程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

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

如何模拟 FromCurrentContext() 调用?有什么我应该做的吗?

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

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

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

谢谢!

推荐答案

由于 FromCurrentContext() 方法是一个静态方法,你不能简单地模拟对它的调用.你还有另外两个选择.

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

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

  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:inetpubwwwrootlah", "blah.html", null, new StringWriter());

HttpContext.Current= new HttpContext(request);

有了这个,它不应该再抛出异常,因为 HttpContext.Current 不为空.

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

围绕对 Raise 的调用创建一个封装类,然后模拟出封装类.

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

这篇关于如何模拟 Elmah 的 ErrorSignal 例程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to MOQ an Indexed property(如何最小起订量索引属性)
Mocking generic methods in Moq without specifying T(在 Moq 中模拟泛型方法而不指定 T)
How Moles Isolation framework is implemented?(Moles Isolation 框架是如何实现的?)
Difference between Dependency Injection and Mocking Framework (Ninject vs RhinoMocks or Moq)(依赖注入和模拟框架之间的区别(Ninject vs RhinoMocks 或 Moq))
How to mock Controller.User using moq(如何使用 moq 模拟 Controller.User)
How do I mock a class without an interface?(如何模拟没有接口的类?)