现在让我们用一个无效的产品ID来测试这个方法的报错效果。
- [TestMethod]
- public void GetProductWithInValidIDThrowsException()
- {
- // Arrange
- IProductRepository productRepository = new StubNullProductRepository();
- ProductService productService = new ProductService(productRepository);
-
- // Act & Assert
- Assert.Throws<ProductNotFoundException>(() => productService.GetByID("invalid-id"));
- }
-
- public class StubNullProductRepository : IProductRepository
- {
- public Product GetByID(string id)
- {
- return null;
- }
-
- public IEnumerable<Product> GetProducts()
- {
- throw new NotImplementedException();
- }
- }
|
在这个例子中,我们为每个测试都做了一个独立的Repository。但我们也可在一个Repository上添加额外的逻辑,例如:
- public class StubProductRepository : IProductRepository
- {
- public Product GetByID(string id)
- {
- if (id == "spr-product")
- {
- return new Product()
- {
- ID = "spr-product",
- Name = "Nice Product"
- };
- }
-
- return null;
- }
-
- public IEnumerable<Product> GetProducts()
- {
- throw new NotImplementedException();
- }
- }
|
在第一种方法里,我们写了两个不同的IProductRepository模拟方法,而在第二种方法里,我们的逻辑变得有些复杂。如果我们在这些逻辑中犯了错,那我们的测试就没法得到正确的结果,这又为我们的调试增加了额外的负担,我们需要找到是业务代码出来错还是测试代码不正确。