我有一个方法,它在内部使用静态 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/