我想为以下控制器操作编写单元测试:
public ActionResult ProductList(int category)
{
IEnumerable<Product> productList = repository.Products.Where(p => p.CategoryId == category);
return PartialView("ProductList", productList);
}
这是我的观点:
@model IEnumerable<POS.Domain.Entities.Product>
@foreach (var p in Model)
{
Html.RenderPartial("_ProductSummary", p);
}
我要测试的是,给定 int 值category
,该ProductList
操作返回 aPartialView
中的适当值productList
。我不确定如何测试IEnumerable<Product> productList
.
到目前为止,这是我的单元测试:
[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); ???
}
我得到 a 是System.InvalidCastException
因为我试图将 a 投射PartialViewResult
到IEnumerable
- 这就是我被卡住的地方。 如何针对productList
控制器中的 IEnumerable 进行测试?
另外,不测试部分视图是否正确生成是不好的做法吗?(我假设如果productList
值是正确的,局部视图将被适当地呈现)