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);
 }
有帮助吗?

解决方案

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

其他提示

Assuming that you can mock the field _productDal, you have to test if the record/object with the corresponding pId was actually deleted.

The mocking of _productDal can be achieved if you inject it in your class, for instance using constructor injection.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top