如何对返回void的方法进行单元测试?(How to unit test a method returning void?)
我正在进行单元测试(C#),我有一些方法可以返回void。我想知道模拟这些方法的最佳方法是什么?
下面是一段代码: -
public void DeleteProduct(int pId) { _productDal.DeleteProduct(pId); }I am doing unit test(C#) and i have some methods which are returning void.I want to know what is the best way to mock those methods ?
Below is the piece of code:-
public void DeleteProduct(int pId) { _productDal.DeleteProduct(pId); }最满意答案
您可以测试的是使用正确的参数调用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)); }What you could test is that ProductDAL.DeleteProduct is called with the correct parameters. This can be accomplished by using dependency injection and mocks!
Sample using Moq as mocking framework:
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); } }Unit test
[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)); }更多推荐
发布评论