[英]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.