Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 875
Dmytro Avatar asked Sep 11 '12 13:09

Dmytro


People also ask

How do you find partial view?

A partial view is sent via AJAX and must be consumed by JavaScript on the client side, while a View is a full postback. That's it. Normally this means that a View is more of a complete web page and a partial view is reserved for individual sections or controls. Realistically, though, you can send the exact same .

How do I render partial views?

Rendering a Partial View You can render the partial view in the parent view using the HTML helper methods: @html. Partial() , @html. RenderPartial() , and @html. RenderAction() .

How do I return a partial view as a string?

Using the ViewEngineResult object, the ViewContext object is determined. Now using the Render function of the ViewEngineResult class, the Partial View is rendered into a StringWriter class object. Finally the StringWriter class object is converted to String which is then returned to the View.


1 Answers

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"

like image 88
Joe Avatar answered Sep 29 '22 07:09

Joe