首页 新闻 会员 周边 捐助

一个神奇的测试问题

0
悬赏园豆:50 [已解决问题] 解决于 2012-06-19 15:12
public ViewResult Edit(int productId)
        {
            Product product = repository.Products.FirstOrDefault(p => p.ProductID == productId);
            return View(product);
        }

这个是原始的方法

测试代码如下:

测试代码1: 

[TestMethod]
        public void Can_Edit_Product()
        {
            // 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"},
                new Product {ProductID = 2, Name = "P2"},
                new Product {ProductID = 3, Name = "P3"},
                new Product {ProductID = 4, Name = "P4"}
            }.AsQueryable());

            // Arrange - create the controller
            AdminController target = new AdminController(mock.Object);


            // Act
            
            //Product p3 = target.Edit(3).ViewData.Model as Product;

            Product p4 = target.Edit(11).ViewData.Model as Product;
            Product p1 = target.Edit(11).ViewData.Model as Product;

            // Assert
            Assert.AreEqual(null, p4);
            //Assert.AreSame(p1, p4);
        }

这个时候测试通过。

请注意:

//Product p3 = target.Edit(3).ViewData.Model as Product;

这一行是注释掉了。

取消注释:

[TestMethod]
        public void Can_Edit_Product()
        {
            // 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"},
                new Product {ProductID = 2, Name = "P2"},
                new Product {ProductID = 3, Name = "P3"},
                new Product {ProductID = 4, Name = "P4"}
            }.AsQueryable());

            // Arrange - create the controller
            AdminController target = new AdminController(mock.Object);


            // Act
            
            Product p3 = target.Edit(3).ViewData.Model as Product;

            Product p4 = target.Edit(11).ViewData.Model as Product;
            Product p1 = target.Edit(11).ViewData.Model as Product;

            // Assert
            Assert.AreEqual(null, p4);
            //Assert.AreSame(p1, p4);
        }

测试就无法通过:

Assert.AreEqual failed. Expected:<(null)>. Actual:<SportsStore.Domain.Entities.Product>.

 

很奇怪啊, 为什么这个时候,p4是Product类型,而不是null呢?

 

谢谢。

问题补充:

人呢?

无尽思绪的主页 无尽思绪 | 初学一级 | 园豆:94
提问于:2012-06-12 15:13
< >
分享
最佳答案
0

问题还比较复杂

无尽思绪 | 初学一级 |园豆:94 | 2012-06-19 14:39
其他回答(1)
0

你能把P4的值跟踪出来吗 ?

另外,你先运行P1,再运行P3,最后运行P4,结果又是如何?

收获园豆:50
无之无 | 园豆:5095 (大侠五级) | 2012-06-14 08:19
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册