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
?
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);
}
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.");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With