测试驱动开发上的五大错误

发表于:2013-3-15 10:38

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:未知    来源:51Testing软件测试网采编

分享:

  现在让我们用一个无效的产品ID来测试这个方法的报错效果。

  1. [TestMethod]  
  2. public void GetProductWithInValidIDThrowsException()  
  3. {  
  4.     // Arrange  
  5.     IProductRepository productRepository = new StubNullProductRepository();  
  6.     ProductService productService = new ProductService(productRepository);  
  7.      
  8.     // Act & Assert  
  9.     Assert.Throws<ProductNotFoundException>(() => productService.GetByID("invalid-id"));  
  10. }  
  11.      
  12. public class StubNullProductRepository : IProductRepository  
  13. {  
  14.     public Product GetByID(string id)  
  15.     {  
  16.         return null;  
  17.     }  
  18.      
  19.     public IEnumerable<Product> GetProducts()  
  20.     {  
  21.         throw new NotImplementedException();  
  22.     }  
  23. }

  在这个例子中,我们为每个测试都做了一个独立的Repository。但我们也可在一个Repository上添加额外的逻辑,例如:

  1. public class StubProductRepository : IProductRepository   
  2. {   
  3.     public Product GetByID(string id)   
  4.     {   
  5.         if (id == "spr-product")   
  6.         {   
  7.             return new Product()   
  8.             {   
  9.                 ID = "spr-product",   
  10.                 Name = "Nice Product" 
  11.             };   
  12.         }   
  13.      
  14.         return null;   
  15.     }   
  16.      
  17.     public IEnumerable<Product> GetProducts()   
  18.     {   
  19.         throw new NotImplementedException();   
  20.     }   
  21. }

  在第一种方法里,我们写了两个不同的IProductRepository模拟方法,而在第二种方法里,我们的逻辑变得有些复杂。如果我们在这些逻辑中犯了错,那我们的测试就没法得到正确的结果,这又为我们的调试增加了额外的负担,我们需要找到是业务代码出来错还是测试代码不正确。

62/6<123456>
价值129的会员专享直播免费赠送,添加微信领取听课名额哦~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计

法律顾问:上海漕溪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2023
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号