【问题标题】:Moq unit test to filter products by their categoriesMoq 单元测试按类别过滤产品
【发布时间】:2013-04-28 02:51:35
【问题描述】:

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

我正在尝试测试是否可以按类别过滤产品。我可以访问 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");
        }

【问题讨论】:

  • **Category1.Name** 应该做什么?
  • 这只是我的类别类中的名称属性。 I have a navigation bar and when a category is selected, it passes that value to my controller and filters the products based on the matching category name.

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


【解决方案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());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多