如何对返回void的方法进行单元测试?(How to unit test a method returning void?)

编程入门 行业动态 更新时间:2024-10-26 22:16:30
如何对返回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)); }

更多推荐

本文发布于:2023-08-07 00:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1458949.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单元测试   方法   void   unit   returning

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!