2

単体テストは初めてなので、これは非常に基本的な質問だと思いますが、検索しても解決策が見つかりませんでした。

製品をカテゴリ別にフィルタリングできるかどうかをテストしようとしています。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");
        }
4

1 に答える 1

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());
于 2013-04-28T03:00:02.303 に答える