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

标签 c# unit-testing mocking void

我正在进行单元测试 (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));
}

关于c# - 如何对返回 void 的方法进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22755028/

相关文章:

java - 程序中途掉网测试效果

java - 是否可以模拟 System.identityHashCode?

node.js - 在测试中模拟对外部服务的 axios 请求

c# - 动态 CRM SDK : Batch update specific fields in entity

c# - 如何使用 Gmail API 检索我的 Gmail 邮件?

c# - MySQL 参数化选择查询连接表问题

c# - Entity Framework 。测试 SaveChanges 是否存在并在方法中的正确位置调用

c# - 从 CodeLens 中排除 <see cref ="class"> xmldoc 引用?

unit-testing - 请解释单元测试

scala - 模拟 Scala 对象和函数