How can I mock Elmah#39;s ErrorSignal routine?(如何模拟 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.
由于
FromCurrentContext()
在内部调用HttpContext.Current
您可以在其中推送一个假上下文.例如:
Since
FromCurrentContext()
internally makes a call toHttpContext.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 例程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何模拟 Elmah 的 ErrorSignal 例程?


- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- C# 中多线程网络服务器的模式 2022-01-01