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

Geo*_*Geo 97 c# asp.net-mvc moq mocking 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).
    ...
 }
Run Code Online (Sandbox Code Playgroud)

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

protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
    base.Initialize(requestContext);
}
Run Code Online (Sandbox Code Playgroud)

在哪里可以获得有关使用Moq模拟我的RequestContext和HttpContext的更多信息?我正在尝试模拟cookie和一般上下文.

tva*_*son 57

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

 controller.ControllerContext = new ControllerContext( context.Object, new RouteData(), controller );
Run Code Online (Sandbox Code Playgroud)


010*_*101 36

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

HttpRequest httpRequest = new HttpRequest("", "http://mySomething/", "");
StringWriter stringWriter = new StringWriter();
HttpResponse httpResponse = new HttpResponse(stringWriter);
HttpContext httpContextMock = new HttpContext(httpRequest, httpResponse);
Run Code Online (Sandbox Code Playgroud)


Cha*_*mar 12

谢谢用户0100110010101.

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

 var currentUrl = Request.Url.AbsoluteUri;
Run Code Online (Sandbox Code Playgroud)

以下是解决问题的方法

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);
Run Code Online (Sandbox Code Playgroud)

可能对其他人有帮助.

  • 这没有用,因为 HttpRequest 中的所有字段都是不可变的 (2认同)

小智 7

下面是我如何使用 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.");
    }
}
Run Code Online (Sandbox Code Playgroud)


Din*_*ruz 6

下面是一个如何设置它的示例:为UnitTests模拟HttpContext HttpRequest和HttpResponse(使用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();
Run Code Online (Sandbox Code Playgroud)

下面是一个如何使用moq编写单元测试以检查HttpModule是否按预期工作的示例:使用Moq封装HttpRequest的HttpModule单元测试

更新:此API已经过重构