ASP.NET MVC - Unit testing RenderPartialViewToString() with Moq framework?

前端 未结 1 1859
长情又很酷
长情又很酷 2021-01-02 22:41

I\'m using this helper method to turn my PartialViewResult into string and returning it as Json - http://www.atlanticbt.com/blog/asp-net-mvc-using-ajax-json-and-partialviews

相关标签:
1条回答
  • 2021-01-02 23:04

    try this:

    public static void SetContext(this Controller controller)
            {
                var httpContextBase = new Mock<HttpContextBase>();
                var httpRequestBase = new Mock<HttpRequestBase>();
                var respone = new Mock<HttpResponseBase>();
                var session = new Mock<HttpSessionStateBase>();
                var routes = new RouteCollection();
                RouteConfigurator.RegisterRoutesTo(routes);
    
                httpContextBase.Setup(x => x.Response).Returns(respone.Object);
                httpContextBase.Setup(x => x.Request).Returns(httpRequestBase.Object);
                httpContextBase.Setup(x => x.Session).Returns(session.Object);
                session.Setup(x => x["somesessionkey"]).Returns("value");
                httpRequestBase.Setup(x => x.Form).Returns(new NameValueCollection());
                controller.ControllerContext = new ControllerContext(httpContextBase.Object, new RouteData(), controller);
                controller.Url = new UrlHelper(new RequestContext(controller.HttpContext, new RouteData()), routes);
            }
    
    0 讨论(0)
提交回复
热议问题