问题
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