如何使用Moq在ASP.NET MVC中模拟HttpContext?

时间:2009-09-21 00:24:36

标签: c# asp.net-mvc mocking moq httpcontext

[TestMethod]
public void Home_Message_Display_Unknown_User_when_coockie_does_not_exist()
{
    var context = new Mock<HttpContextBase>();
    var request = new Mock<HttpRequestBase>();
    context
        .Setup(c => c.Request)
        .Returns(request.Object);
    HomeController controller = new HomeController();

    controller.HttpContext = context; //Here I am getting an error (read only).
    ...
 }

我的基本控制器重写了这个requestContext的Initialize。我试图通过这个,但我没有做正确的事情。

protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
    base.Initialize(requestContext);
}

在哪里可以获得有关使用Moq模拟RequestContext和HttpContext的更多信息?我试图模仿cookie和一般背景。

5 个答案:

答案 0 :(得分:54)

HttpContext是只读的,但它实际上是从您可以设置的ControllerContext派生的。

 controller.ControllerContext = new ControllerContext( context.Object, new RouteData(), controller );

答案 1 :(得分:33)

创建请求,响应并将它们都放到HttpContext:

HttpRequest httpRequest = new HttpRequest("", "http://mySomething/", "");
StringWriter stringWriter = new StringWriter();
HttpResponse httpResponse = new HttpResponse(stringWriter);
HttpContext httpContextMock = new HttpContext(httpRequest, httpResponse);

答案 2 :(得分:10)

感谢用户0100110010101。

它对我有用,在这里我在为下面的代码编写测试用例时遇到了问题:

 var currentUrl = Request.Url.AbsoluteUri;

以下是解决问题的线条

HomeController controller = new HomeController();
//Mock Request.Url.AbsoluteUri 
HttpRequest httpRequest = new HttpRequest("", "http://mySomething", "");
StringWriter stringWriter = new StringWriter();
HttpResponse httpResponse = new HttpResponse(stringWriter);
HttpContext httpContextMock = new HttpContext(httpRequest, httpResponse);
controller.ControllerContext = new ControllerContext(new HttpContextWrapper(httpContextMock), new RouteData(), controller);

可能对其他人有帮助。

答案 3 :(得分:5)

以下是如何进行设置的示例:Mocking HttpContext HttpRequest and HttpResponse for UnitTests (using Moq)

请注意扩展方法,这些方法确实有助于简化此模拟类的使用:

var mockHttpContext = new API_Moq_HttpContext();

var httpContext = mockHttpContext.httpContext();

httpContext.request_Write("<html><body>".line()); 
httpContext.request_Write("   this is a web page".line());  
httpContext.request_Write("</body></html>"); 

return httpContext.request_Read();

以下是如何使用moq编写单元测试以检查HttpModule是否按预期工作的示例:Unit Test for HttpModule using Moq to wrap HttpRequest

更新:此API已重构为

答案 4 :(得分:4)

以下是我使用ControllerContext传递假应用程序路径的方法:

[TestClass]
public class ClassTest
{
    private Mock<ControllerContext> mockControllerContext;
    private HomeController sut;

    [TestInitialize]
    public void TestInitialize()
    {
        mockControllerContext = new Mock<ControllerContext>();
        sut = new HomeController();
    }
    [TestCleanup]
    public void TestCleanup()
    {
        sut.Dispose();
        mockControllerContext = null;
    }
    [TestMethod]
    public void Index_Should_Return_Default_View()
    {

        // Expectations
        mockControllerContext.SetupGet(x => x.HttpContext.Request.ApplicationPath)
            .Returns("/foo.com");
        sut.ControllerContext = mockControllerContext.Object;

        // Act
        var failure = sut.Index();

        // Assert
        Assert.IsInstanceOfType(failure, typeof(ViewResult), "Index() did not return expected ViewResult.");
    }
}