单元测试中的ASP.NET MVC渲染视图

时间:2016-04-05 11:10:03

标签: asp.net-mvc unit-testing razor

我正在尝试为ASP.NET MVC控制器编写集成测试。在我的控制器中,我使用辅助函数将Razor视图呈现为字符串,就像这样

        private string Render(string viewName, object model)
    {
        ViewData.Model = model;
        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
                viewName);
            var viewContext = new ViewContext(ControllerContext, viewResult.View,
                ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);
            viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
            return sw.GetStringBuilder().ToString();
        }
    }

我在Controller动作中使用了这个辅助函数,将视图渲染为字符串,并将其返回给AJAX调用,如下面的动作

    [HttpPost]
    public virtual ActionResult TestAction()
    {
        var model = GetModel(); 
        var razorViewToString = Render("TestAction", model);
        var data = new
        {
            html = razorViewToString
        };
        return Json(data, JsonRequestBehavior.AllowGet);
    }

我为上述行动写了一个测试,如下所示

    [Test]
    public void TestActionTest()
    {
        var request = new Mock<HttpRequestBase>();
        request.SetupGet(x => x.IsAuthenticated).Returns(true);
        var context = new Mock<HttpContextBase>();
        context.SetupGet(x => x.Request).Returns(request.Object);
        var controller = new Controller();
        var routeData = new RouteData();
        routeData.Values.Add("controller", "TestController");
        routeData.Values.Add("action", "TestAction");
        var controllerContext = new ControllerContext(context.Object, routeData, controller);
        ViewEngines.Engines.Clear();
        ViewEngines.Engines.Add(new RazorViewEngine());
        controller.ControllerContext = controllerContext;
        var result = controller.TestAction();
        // assert
    }

当我运行代码时,它会出现这个异常:

enter image description here

显然,因为ControllerContext的DisplayMode为null。我试图模仿它,但它也有同样的错误。

如何在单元测试中渲染视图?

1 个答案:

答案 0 :(得分:-1)

result.View.Render()

然后尝试{{ $product->filters->where("filter_id","10") }}