When it comes to mocking the LINQ DataContext, it’s not an easy task to do, because DataContext (base class) doesn’t implement any interface, so you have to create a wrapper around the DataContext. I decided to follow the Unit Of Work pattern and created also a Generic Repository to access the model classes from the DataContext. I tried to dig around on the internet for articles to direct me in the right direction. All articles on the internet were old and outdated. That is the main reason I decided writing this article describing the method. I have also used this method with Entity Framework. It worked really well, so I highly recommend this method for both LINQ and Entity Framework. Later I will cover the same method with Entity Framework.  

You can get the code from GitHub

The method

The main point is to create a Unit Of Work pattern that handles the context and keeps track of our repositories. The repository is then accessable through a Generic Repository pattern that specifies the same functions for all model classes, mocked or real. Next we create a service layer which handles all business logic. It only contains IUnitOfWork interface, so with IoC / dependency injection we can inject either real or mocked UnitOfWork. The service layer doesn’t care what kind of data it is getting. It just talks to Unit Of Work which then delivers the data. This is so we can test our logic (service layer) in isolation. When you have many services that use the same Unit Of Work instance, you don’t have to worry about DataReader conflicts, because the Unit Of Work only makes a DataContext instance in the constructor, when an instance of UnitOfWork is created.   Student example In this example I will use a model class named “Student”. Because we are working with LINQ our model classes will be auto-generated, but figurately speaking our Student model would look something like this:

public class Student
{
    public int id { get; set; }
    public string name { get; set; }
} 

Generic Repository

I used a Generic Repository pattern to access my model classes. This is so I have generic actions for each model class (add/delete/update/getall, etc).

Here is my IRepository interface:

public interface IRepository<T> where T : class
{
    IQueryable<T> GetAll();
    void Add(T entity);
    void Delete(T entity);
    void DeleteAll(IEnumerable<T> entity);
    void Update(T entity);
    bool Any();
}

Next I created the Repository class that implements the interface. This class will work with DataContext, which is our LINQ DataContext. Later on we will also create a MockRepository that will handle our mocked data, but here is my Repository class:

public class Repository<T> : IRepository<T> where T : class
{
    private DataContext Context;

    public Repository(DataContext ctx)
    {
        Context = ctx;
    }

    public virtual IQueryable<T> GetAll()
    {
        return Context.GetTable<T>();
    }

    public void Add(T entity)
    {
        Context.GetTable<T>().InsertOnSubmit(entity);
    }

    public void Delete(T entity)
    {
        Context.GetTable<T>().DeleteOnSubmit(entity);
    }

    public void DeleteAll(IEnumerable<T> entity)
    {
        Context.GetTable<T>().DeleteAllOnSubmit(entity);
    }

    public void Update(T entity)
    {
        var entry = Context.GetTable<T>().Where(s => s == entity);
        Context.GetTable<T>().Attach(entity);
    }

    public bool Any()
    {
        return Context.GetTable<T>().Any();
    }

    public virtual ITable GetTable()
    {
        return Context.GetTable<T>();
    }
}  

Unit Of Work

Next step is to create the Unit Of Work. We start off by creating an interface that both our LINQ UnitOfWork and our mocked UnitOfWork will implement.

Here is the IUnitOfWork interface:

public interface IUnitOfWork : IDisposable
{
    IRepository<TEntity> GetRepository<TEntity>() where TEntity : class;
    void Save();
} 

Next we create a class that implements our interface. Again, this is the class that works with LINQ DataContext, not our mocked one. Here is the

UnitOfWork class:

public class UnitOfWork<TContext> : IUnitOfWork where TContext : DataContext, new()
{
    private readonly DataContext Context;
    private Dictionary<Type, object> _repositories;
    private bool _disposed;

    // Default constructor that news the context and the dictionary containing all the repositories
    public UnitOfWork()
    {
        Context = new TContext();
        _repositories = new Dictionary<Type, object>();
        _disposed = false;
    }

    // Retrieves the repository for some Model class T
    // If it doesn't exist, we create an instance of it
    public IRepository<T> GetRepository<T>() where T : class
    {
        // Checks if the Dictionary Key contains the Model class
        if (_repositories.Keys.Contains(typeof(T)))
        {
            // Return the repository for that Model class
            return _repositories[typeof(T)] as IRepository<T>;
        }

        // If the repository for that Model class doesn't exist, then create it
        var repository = new Repository<T>(Context);

        // Add it to the dictionary
        _repositories.Add(typeof(T), repository);

        // Return it
        return repository;
    }

    // Saves all changes done to the context
    public void Save()
    {
        Context.SubmitChanges();
    }

    // Disposes the context
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    // Disposes the context only once if not disposed
    protected virtual void Dispose(bool disposing)
    {
        if (!this._disposed)
        {
            if (disposing)
                Context.Dispose();

            this._disposed = true;
        }
    }
}  

Service layer

All of our business logic will be created in a service layer, because the controllers should not contain any logic. This is so all our logic can be in one place and that the same logic can be unit tested with mocked data.

So here is my StudentService class:

public class StudentService
{
    private IUnitOfWork _uow;

    private IRepository<Student> _Student;

    public StudentService(IUnitOfWork uow)
    {
        _uow = uow;

        _Student = _uow.GetRepository<Student>();
    }

    public IEnumerable<Student> GetAllStudents()
    {
        return _Student.GetAll();
    }

    public Student GetStudentByID(int id)
    {
        try
        {
            return _Student.GetAll().Where(s => s.id == id).SingleOrDefault();
        }
        catch (Exception ex)
        {
            throw new Exception("Failure getting student", ex);
        }
    }

    public void DeleteStudentByID(int id)
    {
        try
        {
            Student model = _Student.GetAll().Where(s => s.id == id).SingleOrDefault();
            _Student.Delete(model);
            _uow.Save();
        }
        catch (Exception ex)
        {
            throw new Exception("Failure deleting student", ex);
        }
    }
}   

Mocking

Because LINQ has no interface for DataContext we need to create a seperate implementation of our Repository and UnitOfWork classes, to work with mocked data. It’s a good practice to keep this in a seperate test project, in a namespace/folder called “Mock” or something like that.

Here is my MockRepository class:

public class MockRepository<T> : IRepository<T> where T : class
{
    public List<T> _context;

    public MockRepository(List<T> ctx)
    {
        _context = ctx;
    }

    public virtual IQueryable<T> GetAll()
    {
        return _context.AsQueryable();
    }

    public virtual void Add(T entity)
    {
        _context.Add(entity);
    }

    public virtual void Delete(T entity)
    {
        _context.Remove(entity);
    }

    public virtual void DeleteAll(IEnumerable<T> entity)
    {
        _context.RemoveAll(s => s == entity);
    }

    public virtual void Update(T entity)
    {
        var entry = _context.Where(s => s == entity).SingleOrDefault();
        entry = entity;
    }

    public virtual bool Any()
    {
        return _context.Any();
    }
}

Here is my MockUnitOfWork class:

public class MockUnitOfWork<T> : IUnitOfWork where T : class, new()
{
    private T Context;
    private Dictionary<Type, object> _repositories;

    public MockUnitOfWork()
    {
        Context = new T();
        _repositories = new Dictionary<Type, object>();
    }

    public IRepository<TEntity> GetRepository<TEntity>() where TEntity : class
    {
        if (_repositories.Keys.Contains(typeof(TEntity)))
        {
            return _repositories[typeof(TEntity)] as IRepository<TEntity>;
        }

        var entityName = typeof(TEntity).Name;
        var prop = Context.GetType().GetProperty(entityName);
        MockRepository<TEntity> repository = null;
        if (prop != null)
        {
            var entityValue = prop.GetValue(Context, null);
            repository = new MockRepository<TEntity>(entityValue as List<TEntity>);
        }
        else
        {
            repository = new MockRepository<TEntity>(new List<TEntity>());
        }
        _repositories.Add(typeof(TEntity), repository);
        return repository;
    }

    public void SetRepository<TEntity>(List<TEntity> data) where TEntity : class
    {
        IRepository<TEntity> repo = GetRepository<TEntity>();

        var mockRepo = repo as MockRepository<TEntity>;
        if (mockRepo != null)
        {
            mockRepo._context = data;
        }
    }

    public void Save()
    {
    }

    public void Dispose()
    {
    }
}   

Unit Test

Next we create our unit tests against our service layer. The service layer doesn’t care where it gets the data from. All it knows it talks to Unit Of Work that provides the data. This is so the logic can be unit tested in isolation. But first we need to implement our mocked DataContext with our fake data.

Here is the MockDataContext class:

public class MockDataContext
{
    public List<Student> Student
    {
        get
        {
            return new List<Student>
        {
            new Student
            {
                id = 1,
                name = "John Doe",
            },
            new Student
            {
                id = 2,
                name = "Victor Sagev",
            },
            new Student
            {
                id = 3,
                name = "Wayne Johnson",
            }
        };
        }
    }
}

I created an example StudentServiceTest that tests all functions in the StudentService class. For this I use VisualStudio UnitTest library (Microsoft.VisualStudio.TestTools.UnitTesting).

Here is the StudentServiceTest class:

[TestClass]
public class StudentServiceTest
{
    IUnitOfWork _uow;
    StudentService _studentService;

    [TestInitialize]
    public void SetUp()
    {
        _uow = new MockUnitOfWork<MockDataContext>();
        _studentService = new StudentService(_uow);
    }

    [TestCleanup]
    public void TearDown()
    {
        // Clean resources
    }

    [TestMethod]
    public void TestGetStudentJohnDoe()
    {
        var student = _studentService.GetStudentByID(1);
        Assert.AreEqual(student.name, "John Doe");
    }

    [TestMethod]
    public void TestDeleteStudentJohnDoe()
    {
        try
        {
            _studentService.DeleteStudentByID(1);
        }
        catch(Exception ex)
        {
            Assert.Fail("Expected no exception, but got: " + ex.Message);
        }
    }
}

So here we go. Next time I will use the same method/pattern for Entity Framework, but it’s slight different because you have to create IDataContext that our DataContext and MockDataContext implement. More on that later.