Mocking ITable<T>

I have to do some mocking of an ITable to be able to test some of my code, as you may imagine this is the point where we’re crossing the data boundary… Now, ITable is a total bugger to mock, I’ve tried on (at least) 3 separate occasions to get it mocked, and have only now, finally achieved an 80% solution.

(Nothing is ever 100%)

I’m not using any mock framework, they just take too long to setup (in this case) and instead have a concrete class that implements ITable and uses an IList as it’s base.

Without further ado:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Linq.Expressions;

public class MockTable<T> : ITable<T> where T : class
{
    private readonly IList<T> _entities;

    public MockTable(IList<T> entities)
    {
        _entities = entities;
    }

    #region ITable<T> Members

    public IEnumerator<T> GetEnumerator()
    {
        return _entities.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public Expression Expression 
    { 
        get 
        { 
            return _entities.AsQueryable().Expression; 
        } 
    }

    public Type ElementType 
    { 
        get 
        { 
            return _entities.AsQueryable().ElementType; 
        } 
    }

    public IQueryProvider Provider 
    { 
        get 
        { 
            return _entities.AsQueryable().Provider; 
        } 
    }

    public void InsertOnSubmit(T entity)
    {
        throw new NotImplementedException();
    }

    public void Attach(T entity)
    {
        throw new NotImplementedException();
    }

    public void DeleteOnSubmit(T entity)
    {
        throw new NotImplementedException();
    }
    #endregion ITable<T> Members
}

To use, in your test, let’s say you have an IDataContext (and why not) looking like this:

public interface IDataContext
{
    ITable<Person> People { get; set; }
}

You can then mock this interface like so:

[TestMethod]
public void Something_DoesSomething_WhenSomething()
{
    //Create seed list
    var people = new List<Person>{ new Person{Name = "Chris Skardon"} };
    
    //Create new Mock
    var dataContextMock = new Mock<IDataContext>();
    
    //Setup the People ITable property
    dataContextMock
        .Setup(dc => dc.People)
        .Returns(new MockTable<Person>(people));
    
    /* Asserts etc */
}

It’s obviously not perfect, I haven’t bothered with several methods, but I’ll get to them later…

Print | posted @ Monday, February 6, 2012 9:12 PM

Comments on this entry:

Gravatar # re: Mocking ITable<T>
by Garrett at 11/7/2013 5:00 PM

Thanks very much. I've been trying to figure out how to use Moq to mock an ITable all morning. It appears it wants to use more than one method to achieve the functionality of the Linq query though, so your solution worked beautifully.
Post A Comment
Title:
Name:
Email:
Comment:
Verification: