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

如何使用Moq在ASP.NET MVC中模拟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).
    ...
 }

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

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

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


摇曳的蔷薇
浏览 772回答 3
3回答

慕少森

HttpContext是只读的,但它实际上是从您可以设置的ControllerContext派生的。&nbsp;controller.ControllerContext&nbsp;=&nbsp;new&nbsp;ControllerContext(&nbsp;context.Object,&nbsp;new&nbsp;RouteData(),&nbsp;controller&nbsp;);

回首忆惘然

创建一个请求,响应并将它们都放到HttpContext中:HttpRequest httpRequest = new HttpRequest("", "http://mySomething/", "");StringWriter stringWriter = new StringWriter();HttpResponse httpResponse = new HttpResponse(stringWriter);HttpContext httpContextMock = new HttpContext(httpRequest, httpResponse);

素胚勾勒不出你

它对我有用,在这里我在为下面的代码编写测试用例时遇到了问题:&nbsp;var&nbsp;currentUrl&nbsp;=&nbsp;Request.Url.AbsoluteUri;以下是解决问题的方法HomeController&nbsp;controller&nbsp;=&nbsp;new&nbsp;HomeController();//Mock&nbsp;Request.Url.AbsoluteUri&nbsp;HttpRequest&nbsp;httpRequest&nbsp;=&nbsp;new&nbsp;HttpRequest("",&nbsp;"http://mySomething",&nbsp;"");StringWriter&nbsp;stringWriter&nbsp;=&nbsp;new&nbsp;StringWriter();HttpResponse&nbsp;httpResponse&nbsp;=&nbsp;new&nbsp;HttpResponse(stringWriter);HttpContext&nbsp;httpContextMock&nbsp;=&nbsp;new&nbsp;HttpContext(httpRequest,&nbsp;httpResponse);controller.ControllerContext&nbsp;=&nbsp;new&nbsp;ControllerContext(new&nbsp;HttpContextWrapper(httpContextMock),&nbsp;new&nbsp;RouteData(),&nbsp;controller);可能对其他人有帮助。
打开App,查看更多内容
随时随地看视频慕课网APP