Also i want to know the concept of DI(Dependency Injection) and Mocking(MOQ object) in unit testing
Dependency Injection is the way we make our application adhere to Dependency Inversion Principle, which states that high-level modules should not depend on low-level modules - both should depend on abstractions. Depending on abstractions gives you low-coupling of units in system and ability to give any implementation of abstract dependency to dependent class. And here comes part related to unit-testing - you can give mocked implementation of dependency, which will allow you to verify behavior (see Mocks Aren't Stubs article) of unit under test.
You are already did a good job by making your ProductService
depend on abstractions, and you used DI to inject abstraction implementation to service. What you need to test behavior of service is injecting mocked implementation of abstraction, and setting up expected interaction between ProductService
and mock:
ProductService _productService;
Mock<IProductDal<Product>> _productDalMock;
[TestInitialize]
public void Setup()
{
// create mock of dependency and pass mocked object to service
_productDalMock = new Mock<IProductDal<Product>>();
_productService = new ProductService(productDalMock.Object);
}
[TestMethod]
public void ShouldNotReturnDtosWhenProductsNotFound()
{
// Arrrange
var name = "CreateSave";
var description = "CreateSave";
// setup mocked dal to return empty list of products
// when name and description passed to GetProducts method
_productDalMock.Setup(d => d.GetProducts(name, description))
.Returns(new List<Product>());
// Act
List<ProductDto> actual = _productService.GetProducts(name, description);
// Assert
Assert.False(actual.Any());
// verify all setups of mocked dal were called by service
_productDalMock.VerifyAll();
}
As you can see in test above, you can check whether product service called its dependency with correct parameters, and you can setup what data should dependency return to service. For next test you can setup mock to return list of predefined products. Then you will verify if appropriate dtos were returned by service.