How can I unit test execute an MVC action that returns a PartialViewResult?

I have an Action as follows:

 public PartialViewResult MyActionIWantToTest(string someParameter) { // ... A bunch of logic return PartialView("ViewName", viewModel); } 

When I check the result, it has several properties, but they are either null or empty. The only property that has anything is the ViewEngineCollection , which does not contain anything specific to my method.

Does anyone have some sample code that checks for PartialViewResult ?

+4
source share
2 answers

Let's say you have an Action that looks something like this:

 public PartialViewResult MyActionIWantToTest(string someParameter) { var viewModel = new MyPartialViewModel { SomeValue = someParameter }; return PartialView("MyPartialView", viewModel); } 

Note: MyPartialViewModel is a simple class with one property - SomeValue .

An NUnit example might look like this:

 [Test] public void MyActionIWantToTestReturnsPartialViewResult() { // Arrange const string myTestValue = "Some value"; var ctrl = new StringController(); // Act var result = ctrl.MyActionIWantToTest(myTestValue); // Assert Assert.AreEqual("MyPartialView", result.ViewName); Assert.IsInstanceOf<MyPartialViewModel>(result.ViewData.Model); Assert.AreEqual(myTestValue, ((MyPartialViewModel)result.ViewData.Model).SomeValue); } 
+8
source

The accepted answer did not help me. I did the following to solve the problem I saw.

This was my action:

  [Route("All")] public ActionResult All() { return PartialView("_StatusFilter",MyAPI.Status.GetAllStatuses()); } 

I had to give the result to the type so that it worked. I used PartialViewResult for my action, returning Partial View, unlike other actions that return a full view and use View Result. This is my testing method:

  [TestMethod] public void All_ShouldReturnPartialViewCalledStatusFilter() { // Arrange var controller = new StatusController(); // Act var result = controller.StatusFilter() as PartialViewResult; // Assert Assert.AreEqual("_StatusFilter", result.ViewName, "All action on Status Filter controller did not return a partial view called _StatusFilter."); } 
+1
source

Source: https://habr.com/ru/post/1332703/


All Articles