Moq单元测试按类别过滤产品

时间:2013-04-28 02:51:36

标签: unit-testing asp.net-mvc-4 moq vs-unit-testing-framework

我是单元测试的新手,所以我确信这是一个非常基本的问题,但是当我搜索它时,我找不到解决方案。

我正在尝试测试是否可以按类别过滤产品。我可以访问Product类中的所有属性,但不能访问Category类中的属性。例如,它找不到Category1.Name。谁能告诉我我做错了什么?

这是我的产品类;

 public partial class Product
    {
        public int ProductID { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public decimal Price { get; set; }
        public int CategoryID { get; set; }

        public virtual Category Category1 { get; set; }
    }

这是我的考验;

 [TestMethod]
        public void Can_Filter_Products()
        {
            //Arrange

            Mock<IProductRepository> mock = new Mock<IProductRepository>();
            mock.Setup(m => m.Products).Returns(new Product[]
            {
                new Product {ProductID=1,Name="P1", **Category1.Name** = "test1" },
                new Product {ProductID=2,Name="P2", **Category1.Name** = "test2"},
                new Product {ProductID=3,Name="P3", **Category1.Name** = "test1"},
                new Product {ProductID=4,Name="P4", **Category1.Name** = "test2"},
                new Product {ProductID=5,Name="P5", **Category1.Name** = "test3"},
            }.AsQueryable());

            //Arrange create a controller and make the page size 3 items
            ProductController controller = new ProductController(mock.Object);
            controller.PageSize = 3;

            //Action
            Product[] result = ((ProductsListViewModel)controller.List("test2", 1).Model).Products.ToArray();

            //Assert - check that the results are the right objects and in the right order.
            Assert.AreEqual(result.Length, 2);
            Assert.IsTrue(result[0].Name == "P2" && result[0].Category1.Name == "test2");
            Assert.IsTrue(result[1].Name == "P4" && result[1].Category1.Name == "test2");
        }

1 个答案:

答案 0 :(得分:1)

在模拟设置中,请尝试以下方法:

        mock.Setup(m => m.Products).Returns(new[]
        {
            new Product {ProductID=1,Name="P1", Category1 = new Category { Name = "test1"} },
            new Product {ProductID=2,Name="P2",  Category1 = new Category { Name = "test1"} }
        }.AsQueryable());