Skip to main content
 首页 » 编程设计

c#之如何对返回 void 的方法进行单元测试

2024年02月13日12shihaiming

我正在进行单元测试 (C#),并且我有一些返回 void 的方法。我想知道模拟这些方法的最佳方法是什么?

下面是一段代码:-

 public void DeleteProduct(int pId) 
 { 
         _productDal.DeleteProduct(pId); 
 } 

请您参考如下方法:

您可以测试的是使用正确的参数调用 ProductDAL.DeleteProduct。 这可以通过使用依赖注入(inject)和模拟来完成!

示例使用 Moq作为模拟框架:

public interface IProductDal 
{ 
    void DeleteProduct(int id); 
} 
 
public class MyService 
{ 
    private IProductDal _productDal; 
 
    public MyService(IProductDal productDal) 
    { 
        if (productDal == null) { throw new ArgumentNullException("productDal"); } 
        _productDal = productDal; 
    } 
 
    public void DeleteProduct(int id) 
    { 
        _productDal.DeleteProduct(id); 
    } 
} 

单元测试

[TestMethod] 
public void DeleteProduct_ValidProductId_DeletedProductInDAL() 
{ 
    var productId = 35; 
 
    //arrange 
    var mockProductDal = new Mock<IProductDal>(); 
    var sut = new MyService(mockProductDal.Object); 
 
    //act 
    sut.DeleteProduct(productId); 
 
    //assert 
    //verify that product dal was called with the correct parameter 
    mockProductDal.Verify(i => i.DeleteProduct(productId)); 
}