簡體   English   中英

如何對返回void的方法進行單元測試?

[英]How to unit test a method returning void?

我正在做單元測試(C#),我有一些返回void的方法。我想知道模擬這些方法的最佳方法是什么?

以下是一段代碼:-

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

假設您可以模擬_productDal字段,則必須測試是否已刪除具有相應pId的記錄/對象。

如果將_productDal注入類,例如使用構造函數injection ,就可以實現。

您可以測試的是使用正確的參數調用了ProductDAL.DeleteProduct。 這可以通過使用依賴注入和模擬來完成!

使用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));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM