我试图为依赖于HttpContext对象的几个方法编写一些单元测试。我已经提出了以下课程,但我不认为它是最好的方式。单元测试Webform 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);
}
有没有实现这一个更好的方式,什么时候我开始添加更多的虚拟那将是更清洁数据。