asp.net-mvc-3 - Elmah 错误日志记录 FromCurrentContext 在单元测试时中断

标签 asp.net-mvc-3 unit-testing moq elmah

当使用 Moq 编写单元测试时,每当我调用 Elmah.ErrorSignal.FromCurrentContext 时,它都会失败并出现空引用异常。我能够模拟 ControllerContext 并且我想只使用这样的错误日志命令..

Elmah.ErrorSignal.FromContext(ControllerContext.HttpContext).Raise(e);

但不幸的是,ControllerContext.HttpContext 的类型为 HttpContextBase,并且无法使用此错误日志记录方法。

有没有更好的方法直接调用 Elmah 错误日志记录?不幸的是,Application.HttpContext 对象不能被模拟(下面的示例),否则也可以达到目的。

模拟ApplicationApplication.HttpContext:

ctrlCtx.SetupGet(x => x.HttpContext.ApplicationInstance)
           .Returns(new Mock<HttpApplication>().Object);
ctrlCtx.SetupGet(x => x.HttpContext.ApplicationInstance.Context)
           .Returns(new Mock<HttpContext>().Object);

产生错误:

非虚拟(在 VB 中可重写)成员上的设置无效

最佳答案

虽然您无法模拟 HttpContext,但您可以在测试中设置 HttpContext.Current。

var req = new HttpRequest(string.Empty, "https://www.domain.tld", null);
var res = new HttpResponse(null);
HttpContext.Current = new HttpContext(req, res);

但我不确定 Elmah 使用了上下文的哪些部分。

第三方编辑:
ELMAH 还需要 System.Web.HttpContext.Current.ApplicationInstance

Dim req As System.Web.HttpRequest = New System.Web.HttpRequest(String.Empty, "https://www.domain.tld", Nothing)
Dim res As System.Web.HttpResponse = New System.Web.HttpResponse(Nothing)
System.Web.HttpContext.Current = New System.Web.HttpContext(req, res)

System.Web.HttpContext.Current.ApplicationInstance = New System.Web.HttpApplication()

否则它会抛出异常,因为应用程序名称为 NULL。

进一步编辑:
这是 C# 中的最终代码:

var req = new HttpRequest(string.Empty, "https://www.domain.tld", null);
var res = new HttpResponse(null);
HttpContext.Current = new HttpContext(req, res) 
     {ApplicationInstance = new HttpApplication()};

关于asp.net-mvc-3 - Elmah 错误日志记录 FromCurrentContext 在单元测试时中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10657961/

相关文章:

jquery - 在控件中输入文本后,CKEditor onSubmit 不起作用

asp.net-mvc-3 - 如何在 Orchard 的替代 View 中包含模块资源?

java - bpmn - JavaDelegate 实现的简单测试

c# - 使用最小起订量抛出异常模拟 IMemoryCache

c# 模拟接口(interface) vs 模拟类

asp.net-mvc-3 - 从 MVC 应用程序中的 EF Code-First DbContext 类生成 SQL CE 数据库

asp.net-mvc-3 - ASP.NET MVC 3 Ninject 自定义成员资格和角色提供程序

node.js - 单元测试快速应用程序

c# - 在 .Net Core 中测试 Controller 总是返回 false?

c# - 无法创建搜索响应对象 - 我们如何在 Nest 中模拟搜索响应?