문제

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