如何测试PARTIAL视图是在C#ASP .NET MVC中呈现的

时间:2012-09-11 13:12:19

标签: c# asp.net-mvc-3 unit-testing view partial-views

我有一个视图,它内部有部分视图渲染:

<div class="partialViewDiv">
    @Html.RenderPartial("partial", Model.SomeModelProperty);
</div>

一个控制器,它返回此视图

public ActionResult Action()
        {
            ...
            var model = new SomeModel(){SomeModelProperty = "SomeValue"}
            return View("view", model);
        }

我知道如何测试视图:

[TestMethod]
public void TestView()
{
   ...
   var result = controller.Action();

   // Assert
   result.AssertViewRendered().ForView("view").WithViewData<SomeModel>();
}

但是当我打电话时

result.AssertPartialViewRendered().ForView("partial").WithViewData<SomeModelPropertyType>();

我收到此错误消息

Expected result to be of type PartialViewResult. It is actually of type ViewResult.

我做错了什么?

2 个答案:

答案 0 :(得分:3)

  

我做错了什么?

您正在测试控制器:此类测试实际上是模拟视图,只是验证控制器是否正在返回预期的视图(和模型)。

因为使用PartialView“部分”的视图“视图”不参与测试,所以你无法测试它是否正在按预期进行。

一般来说,大多数人都没有单元测试视图;但如果你想这样做,请查看this blog或google查看“MVC单元测试视图”

答案 1 :(得分:2)

更改

return View(model); 

return PartialView(model);

异常说明了一切。您期望获得部分视图结果,但是您将返回视图结果。