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.Currentyou 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 例程?
基础教程推荐
- C# 从 List<List<int>> 中删除重 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
