1

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);
 }
Pawan
  • 2,150
  • 11
  • 45
  • 73
  • You don't 'mock' methods of the unit you want to test. You may need to mock some of its dependencies though. – haim770 Mar 31 '14 at 06:45
  • possible duplicate of [Unit testing void methods?](http://stackoverflow.com/questions/246038/unit-testing-void-methods) – Jeroen Vannevel Mar 31 '14 at 13:27

2 Answers2

2

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.

Maarten
  • 22,527
  • 3
  • 47
  • 68
  • I would say its very bad practise to mock the dependencies like a database!! – Neel Mar 31 '14 at 06:47
  • 1
    @Neel And why is that? Mocking is something you only do for testing purposes. And if you want to **test** this method, then looking at the body of the method and concluding that all it does is 'forward' the call to the `_productDal` field, then all you have to test is that the `_productDal` is actually receiving the call. Which you can verify if you **mock** that object. – Maarten Mar 31 '14 at 06:49
  • @Neel mocking its just for untestable dependency, like file system, database, etc... – ale Mar 31 '14 at 06:51
2

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));
}
LostInComputer
  • 15,188
  • 4
  • 41
  • 49