views:

44

answers:

1

Hi, I am using EF4, Microsoft.Entity.CTP, and the latest MOQ. I am trying to create a generic repository class and moq the DBContext using MOQ. Whenever I run my moq test I get "object reference not set to an instance of an object" on this.context.Set().Add(entity); and I don't understand why. The code runs ok without a moq.

public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
{
    private IContext context;

    public GenericRepository(IContext context)
    {
        this.context = context;
    }

    public IList<TEntity> List
    {
        get { return context.Set<TEntity>().ToList(); }
    }

    public void Create(TEntity entity)
    {
        this.context.Set<TEntity>().Add(entity);
        this.context.SaveChanges();
    }
}

var mock = new Mock<IContext>();
GenericRepository<Product> producRepository = new GenericRepository<Product>(mock.Object);

mock.Setup(x => x.Product.Add(productType));
mock.Setup(x => x.SaveChanges());

productRepository.Create(product);
mock.VerifyAll();
A: 

You need to mock out the list implementation behind Set. I'm not at the compute ATM but iirc it's an IDbSet.

Daz Lewis