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

Dmy*_*tro 5 c# unit-testing partial-views view asp.net-mvc-3

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

<div class="partialViewDiv">
    @Html.RenderPartial("partial", Model.SomeModelProperty);
</div>
Run Code Online (Sandbox Code Playgroud)

还有一个控制器,它返回这个视图

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

如何测试视图呈现我知道:

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

   // Assert
   result.AssertViewRendered().ForView("view").WithViewData<SomeModel>();
}
Run Code Online (Sandbox Code Playgroud)

但是当我打电话的时候

result.AssertPartialViewRendered().ForView("partial").WithViewData<SomeModelPropertyType>();
Run Code Online (Sandbox Code Playgroud)

我收到此错误消息

Expected result to be of type PartialViewResult. It is actually of type ViewResult.
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Joe*_*Joe 3

我究竟做错了什么?

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

因为渲染 PartialView“部分”的 View“视图”不参与测试,所以你无法测试它是否按照你的预期进行。

一般来说,大多数人不会对视图进行单元测试;但如果你想这样做,请查看此博客或谷歌搜索“MVC 单元测试视图”