I want to write a unit test for the following controller action:
public ActionResult ProductList(int category)
{
IEnumerable<Product> productList = repository.Products.Where(p => p.CategoryId == category);
return PartialView("ProductList", productList);
}
and this is my view:
@model IEnumerable<POS.Domain.Entities.Product>
@foreach (var p in Model)
{
Html.RenderPartial("_ProductSummary", p);
}
What I want to test is that given the int value category, the ProductList action returns a PartialView with the appropriate values in productList. I am not sure how to test the value of the IEnumerable<Product> productList.
Here is my unit test so far:
[TestMethod]
public void ProductListReturnsAppropriateProducts()
{
// Arrange
// - create the mock repository
Mock<IProductRepository> mock = new Mock<IProductRepository>();
mock.Setup(m => m.Products).Returns(new Product[] {
new Product {ProductId = 1, Name = "P1", CategoryId = 1},
new Product {ProductId = 2, Name = "P2", CategoryId = 2},
new Product {ProductId = 3, Name = "P3", CategoryId = 1},
new Product {ProductId = 4, Name = "P4", CategoryId = 2},
new Product {ProductId = 5, Name = "P5", CategoryId = 3}
}.AsQueryable());
// Arrange - create a controller
ProductController controller = new ProductController(mock.Object);
// Action
IEnumerable<Product> result1 = (IEnumerable<Product>)controller.ProductList(1);
//IEnumerable<Product> result2 = (IEnumerable<Product>)controller.ProductList(2); ???
// Assert
Assert.AreEqual(result1, 2);
// Assert.AreEqual(result2, 2); ???
}
I get a System.InvalidCastException because I am trying to cast a PartialViewResult to an IEnumerable – which is where I’m stuck. How do I target the IEnumerable productList in my controller for testing?
Also, would it be bad practice to not test that the partial view is generated correctly? (I am assuming that if the productList value is correct, the partial view will be rendered appropriately)
I found a solution that appears to cover what I need it to:
I was going to have several PartialViewResult values – but I began to have issues with testing multiple Controller Action results simultaneously.