Unit testing repository pattern using Moq, Shouldly in xUnit framework part 1

Now that you have implemented Repository pattern with Unit of work implementation for your Ntier solution data access layer (DAL) ; let’s talk about Unit testing infrastructure that we have in place – my ORM of choice is Entity Framework yours’s could be Nhibernate however the concepts are much the same

Here is my implementation structure for Ntier solution as I will be talking about layering and cross cutting concerns in the projects.

Install-package Moq
Install-package xUnit
Install-package Shouldly

Moq: Allows us to mock functionality that needs to be tested
xUnit: Unit testing framework based on xUnit testing pattern
Shouldly: Makes assertion clean and readible

I then added a class Called PersonRepositoryTest to test my Person repository implementation that is going to manage person data from sample AdventureWorks2012 database available from Microsoft.


In the PersonRepositoryTest I am going to validate PersonRepository implementation listed below:


Without going too much into the details of the abstract class Generic Repository ; it basically has CRUD operations that can be overridden in the implementation of Repository classes.

The first operation that we will be testing is Add Person object to the repository

The [Fact] decorative attribute is the Test method for xUnit framework, we will then tell Moq to create a new Moq object with IPersonRepository and then check to see if the Add person works with the Times.Once() method to verify the Moq details

The next method will verify if we are able to get Person data using GetPersonById() from the repository

And then mocking implementation of Delete() using the repository

In part 2 I will show how to unit test other aspects of the ntier solution