Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I unit test 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 inspect the result, It has a few properties, but they are either null, or empty. The only property that has anything is the ViewEngineCollection which doesn't contain anything specific to my method.

Does anyone have some example code that tests a PartialViewResult?

like image 482
Robert Avatar asked Dec 19 '10 23:12

Robert


2 Answers

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 only one property - SomeValue.

An NUnit example may 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);
}
like image 112
Jonathan Avatar answered Sep 28 '22 03:09

Jonathan


The accepted answer did not work for me. I did the following to resolve the test failure I was seeing.

This was my action:

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

I had to give the result a type in order for it to work. I used PartialViewResult for my action returning a Partial View, as opposed to my other actions that return a full view and use View Result. This is my test 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.");
  }
like image 36
mgilberties Avatar answered Sep 28 '22 01:09

mgilberties