1

我试图为依赖于 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);
    }

有没有更好的方法来实现这一点,当我开始添加更多虚拟数据时会更干净。

4

2 回答 2

1

HttpContext 模拟起来真的很复杂。我建议将依赖项更改为提供您需要的接口,然后有两个实现:一个真实的,使用 HttpContext 和一个用于测试的 Mock 。

如果您无论如何都想模拟它并且您的代码可以解决问题,请保持这种状态。

另一种选择是为 MSTest 使用 ASP.NET 主机类型。在这种情况下,您将执行一个实际请求,并且您的 HttpContext 将在那里:

[TestMethod]
[HostType("ASP.NET")]
[AspNetDevelopmentServerHost(@"$(SolutionDir)\Tests", "/")]
[UrlToTest("http://localhost:1234/TestPage.aspx")]
public void MyTest()
{
    Page page = testContextInstance.RequestedPage;
    ...
}
于 2012-06-19T16:24:04.360 回答
1

HttpContextWrapper 和 HttpContextBase .NET 类是为模拟目的而创建的,例如http://www.codemerlin.com/2011/07/mocking-httpcontext-httpresponse-httprequest-httpsessionstate-etc-in-asp-net/

于 2012-06-19T16:54:20.083 回答