c# - 在单元测试中设置 HttpContext.Current.Application 键

标签 c# asp.net asp.net-mvc asp.net-mvc-5

我有一个方法,它在内部使用静态 HttpContext.Current.Application 来存储键值对,然后在整个应用程序中检索它。

现在,我要做的是对该方法进行单元测试。我目前拥有的是:

private const string Foo = "foobar";

[TestInitialize]
public void InitializeContext()
{
    HttpContext.Current = new HttpContext(new HttpRequest(null, "http://tempuri.org", null), new HttpResponse(null));
    HttpContext.Current.Application["fooKey"] = Foo;
}

[TestCleanup]
public void DisposeContext()
{
    HttpContext.Current = null;
}

很好,但是当我尝试在 TestMethod 中转换该值时,该值为 null。

var fooValue = (string)HttpContext.Current.Application["fooKey"];

显然,我正在测试的方法中的值为空。

到目前为止,我尝试的是模拟上下文 - 效果不佳。然后在SO上看到了fake HTTP context的解决方案,还是不行。我什至尝试接受 HttpApplicationStateBase/HttpApplicationStateWrapper 并处理它们,但它变得一团糟,我觉得有比这更简单的解决方案。

最佳答案

我最后做的是使用 this惊人的图书馆。对于那些想知道为什么没有任何效果的人,this StackOverflow question 解释了一个类似的问题(奇怪我问之前怎么找不到它)。

根据 Jeff Sternal 的回答:

HttpContext.Application is supplied by a private singleton that you can't access normally.

You may be able to set this via reflection, but I personally wouldn't even bother.

Instead you should isolate your testable code from global state like HttpContext.Current: just pass the value you're looking for into the method you want to test.

You can see the problem clearly looking at the code in Reflector (or in the .NET source if you've downloaded that): the HttpContext.Application get accessor returns a new HttpApplicationState instance every time you call it unless something (like the ASP.NET framework) sets HttpApplicationFactory._theApplicationFactory._state.

最终,我做了类似的事情:

using (HttpSimulator simulator = new HttpSimulator())
{
    simulator.SimulateRequest(new Uri("http://localhost/"));
    HttpContext.Current.Application.Add("fooKey", Foo);
    this.httpContext = HttpContext.Current;
}

然后将保存的引用传递给我的方法。

关于c# - 在单元测试中设置 HttpContext.Current.Application 键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35525232/

相关文章:

c# - 用 C++ CLI 编写的 DOTNET 包装器 native 传递结构的最佳方式?

c# - 本地主机连接错误

javascript - 如何为每个网站禁用 iframe 右键单击

c# - 清除字段按钮(重定向不起作用)?

c# - 来自数据源的 Linq 查询,其中...像 '%%' 或 ...像 '%%'

c# - 如何实现类似SO的url重写

c# - Visual Studio MVC 5 无需密码登录

c# - 静态状态列表上的 DropDownListFor

c# - 确保所有线程都关闭或强行关闭一个线程?

asp.net - 为什么在设置 AssociatedUpdatePanelId 时不会触发更新进度?