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呢?
谢谢。
人呢?
问题还比较复杂
你能把P4的值跟踪出来吗 ?
另外,你先运行P1,再运行P3,最后运行P4,结果又是如何?