poniedziałek, 18 marca 2013

Generic Repository (+ mocking and unit testing in MVC)

Last week I was trying to write a small part of simple Data Access Layer. There wouldn’t be anything hard to do, if not the fact that I really wanted to connect this with mocking. After the initial research and “let’s start coding – it can’t be that difficult” approach, which as you can imagine slightly failed, I decided to look for a design pattern which is responsible for dealing with such scenario. I knew that there has to be something.

Now I can’t remember how, but I landed on a page describing the Repository pattern. After a few hours I succeeded and had some working, unit tested and easy-to-expand code. And that’s the topic of today’s post – how to add another layer of abstraction between ASP.NET MVC and Entity Framework to enable easy mocking and unit testing.

To start with something – what’s a Repository design pattern? When to use it? MSDN lists a few reasons like: - Isolation of the data layer to support unit testing, - Implementation of caching for the data source, - Separation of business logic from data access layer, - Usage of strongly typed entities to identify problems at compile time, - Application of domain model in order to simplify the business logic.

Having even a little knowledge about Entity Framework should be enough to be a little suspicious here. “Isn’t EF solving most of these use cases?” – you would ask. And you’re absolutely right! It solves, but “most of them”. What about the data layer isolation? What about a possibility to mock this layer? It’s a part when Repository pattern comes handy! OK, let’s dive into implementation. In order to fully understand the below code, I strongly encourage you to take a look at Tugberk Ugurlu’s article, which inspired me to write this post. First of all – we have our IGenericRepository interface, which can be created upon any class. It contains the most basic methods:
namespace DataAccess.Repositories.Interfaces
{
    public interface IGenericRepository where T : class
    {
        IQueryable GetAll();
        IQueryable FindBy(Expression> predicate);
        void Add(T entity);
        void Delete(T entity);
        void Edit(T entity);
        void Save();
    }
}
Next, I created an abstract class that implements this interface. Class is called GenericRepository.cs. Why is it abstract? Because then I don’t need to explicitly implement every method for each of my repository interfaces. What’s more interesting here? GenericRepository accepts two generic parameters. TContext has to inherit from a DbContext class and contains a parameterless constructor. T can be any class. In fact it will be my domain object, such as User. Then I have an implementation of IGenericRepository methods. Each of these methods is marked as a virtual, so it can be overridden in child class. Last thing – Context property is publicly available, so I can extend my child repositories in a way, I want them to be.
namespace DataAccess.Repositories
{
    public abstract class GenericRepository : IGenericRepository
        where T : class
        where TContext : DbContext, new()
    {
        private TContext _entities = new TContext();

        public TContext Context
        {
            get { return _entities; }
            set { _entities = value; }
        }

        public IQueryable GetAll()
        {
            return _entities.Set();
        }

        public IQueryable FindBy(Expression> predicate)
        {
            return _entities.Set().Where(predicate);
        }

        public void Add(T entity)
        {
            _entities.Set().Add(entity);
        }

        public void Delete(T entity)
        {
            _entities.Set().Remove(entity);
        }

        public void Edit(T entity)
        {
            _entities.Entry(entity).State = EntityState.Modified;
        }

        public void Save()
        {
            _entities.SaveChanges();
        }
    }
}
For each of my entities I’ll have a separate pair of repository interface and implementation. Continuing with an example of Users repository:
namespace DataAccess.Repositories.Interfaces
{
    public interface IUserRepository : IGenericRepository
    {
        User GetSingle(string userName);
    }
}

namespace DataAccess.Repositories
{
    public class UserRepository : GenericRepository, IUserRepository
    {
        public User GetSingle(string userName)
        {
            return Context.Users.SingleOrDefault(u => u.Username == userName);
        }
    }
}
As you can see – with the usage of Context property, I extended the base set of GenericRepository properties, implementing GetSingle method. It makes logical sense – you can’t say that there will be one common method to get a single object from every entity set. You could create a GetSingleById method in GenericRepository abstract class – but it’s much more meaningful to select a user by his username, than his Id.

That’s all regarding the technical implementation of generic Repository pattern. Now let’s jump into the part, which was mentioned at the very beginning – how to write unit tests for such implementation? First – a little bit of installation. Using “Manage NuGet Packages” dialog install Ninject.MVC3 package for the DataAccess project and Moq with NUnit for the Tests project. After the installation of Ninject, you’ll notice that App_Start folder with NinjectWebCommon.cs file was added to your DataAccess project. It’s the place where you’ll say – “Hey! Everytime, you’ll see a call to IUserRepository interface – you should return a UserRepository implementation!”: 

 

 private static void RegisterServices(IKernel kernel)
 {
     kernel.Bind().To();
 }   
And last, but not least – here’s a short mock for testing GetAll() method in UserRepository. Thanks to such mocking – we don’t need a connection to the database to be able to test the data access layer.
namespace Tests
{
    [TestFixture]
    class ProfileControlllerTests
    {
        private IUserRepository _userRepo;

        [TestFixtureSetUp]
        public void Initialize()
        {
            var mock = new Mock();
            mock.Setup(m => m.GetAll())
                .Returns(new[]
                    {
                        new User {Id = 1, Username = "Marian", Password = "jasnepelne.blogspot.com"},
                        new User {Id = 2, Username = "Jaro", Password = "fifa2013"}
                    }.AsQueryable());

            _userRepo = mock.Object;
        }

        [Test]
        public void GetAll_ReturnTwoUsers()
        {
            Assert.AreEqual(2, _userRepo.GetAll().Count());
        }
    }
}