質問

I am new to unit testing so I am sure this is a very basic question, but I couldn't find a solution when I searched for it.

I am trying to test to see if I can filter products by their categories. I can access all the properties in my Product class but not the ones in my Category class. For example, it doesn't find Category1.Name. Can anyone tell me what I'm doing wrong?

This is my product class;

 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; }
    }

This is my test;

 [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");
        }
役に立ちましたか?

解決

In your mock setup, try this instead:

        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());
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top