Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test Repository Pattern with ADO.NET Entity Framework?

While using Repository pattern I find it difficult to understand the reason of designing the software with TDD technique while in reality you will have to implement the Interface for your repository in your persistence dataset.

To make my point clear I will submit an example:

I have the following Interface on my domain model:

public interface IUserRepository
{
    IQueryable<User> FindAllUsers();
    void AddUser(User newUser);
    User GetUserByID(int userID);
    void Update(User userToUpdate);
}

I have the following implementation of the interface for testing purposes:

public class FakeUserRepository : IUserRepository
{
    private IList<User> _repository;

    public FakeUserRepository()
    {
        _repository = new List<User>();
        ... //create all users for testing purposes

    }

    public IQueryable<User> FindAllUsers()
    {
        return _repository.AsQueryable<User>(); //returns all users
    }

Now I create a few tests:

  1. Can_Add_User
  2. Can_Add_Account for a User
  3. Can_Add_ShareSpace for a an account of a user with another user.

My question is, after I test all these with my FakeUserRepository implementation, I have to go back and implement the IUserRepository on my actual persistence dataset (i.g. SQL), and I have to implement again the code, so my unit testing is not actually checking the code that I am actually using on my application.

Maybe I am missing something.

Thanks as always!

Below then my Persistent data access repository which is the one that is supposed to be under test (by my mind at least), but then I should not test hooked to the database:

public class SQLUserRepository : IUserRepository
{
    private BusinessDomainModel.EntityModel.BusinessHelperAccountDBEntities _repository;

    public SQLUserRepository()
    {
        _repository = new BusinessHelperAccountDBEntities();
    }

    #region IUserRepository Members

    public IQueryable<User> FindAllUsers()
    {
        return _repository.UserSet.AsQueryable();
    }
like image 840
Geo Avatar asked Oct 01 '09 00:10

Geo


1 Answers

Never test a mock. The class under test should always be a real instance of the class, though you can and should mock any of its dependencies so you can test it in isolation.

like image 170
tvanfosson Avatar answered Sep 19 '22 10:09

tvanfosson