我试图为依赖于 HttpContext 对象的几个方法编写一些单元测试。我想出了以下课程,但我认为这不是最好的方法。
internal class HttpContextMocking
{
public static HttpContext Context()
{
HttpContext context = new HttpContext(new SimpleWorkerRequest("", "", "", null, new StringWriter()));
context.Cache.Insert("SomeName", "value", null, DateTime.Now.AddMinutes(3), TimeSpan.Zero);
return context;
}
然后我在我的单元测试中通过以下方式调用这个模拟 HttpContext:
[TestMethod]
[TestCategory("Web")]
public void Get()
{
HttpContext.Current = HttpContextMocking.Context();
object result = CacheUtility.Get("NonExistentItem");
Assert.IsNull(result);
}
有没有更好的方法来实现这一点,当我开始添加更多虚拟数据时会更干净。