如何模拟 Elmah 的 ErrorSignal 例程?

时间:2023-02-26
本文介绍了如何模拟 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 例程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:C# 如何模拟 Configuration.GetSection("foo:bar").Get&am 下一篇:为什么我们需要模拟框架?

相关文章

最新文章