How to test PARTIAL view was rendered in C# ASP .NET MVC

一曲冷凌霜 提交于 2020-01-02 04:54:06

问题


I have a view and it has partial view rendering inside:

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

And a controller, which returns this view

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

How to test view was rendered i know:

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

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

but when I call

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

I get this error message

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

What am I doing wrong?


回答1:


What am I doing wrong?

You're testing the controller: such tests essentially mock the view and just verify that the controller is returning the expected view (and model).

Because the View "view" that renders the PartialView "partial" is not involved in the testing, so you can't test whether it's doing what you expect.

In general, most people don't unit test Views; but if you want to do so look at this blog or google for "MVC unit test view"




回答2:


Change

return View(model); 

To

return PartialView(model);

Exception says it all. You are expecting a partial view result, but you are returning a view result.



来源:https://stackoverflow.com/questions/12370532/how-to-test-partial-view-was-rendered-in-c-sharp-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!