Mocking dbset<T> where method returns notSupportedException

Viewed 1603

I'm trying to Mock the where clause of the dbset of my generic repository, and no idea why I'm getting a System.NotSupported Exception. I'm quite new into mocking, so I have no clue why this is happening.

private List<StubEntity> _data;
private Repository<StubEntity> _repository;

[TestInitialize]
public void TestInitialize()
{
    _data = new List<StubEntity>
    {
        new StubEntity {Id = 1, Name = "Entity 1"},
        ...
    };
    var queryableData = _data.AsQueryable();

    var mockDbSet = new Mock<DbSet<StubEntity>>();
    mockDbSet
        .Setup(m => m.Where(It.IsAny<Expression<Func<StubEntity, bool>>>()))
        .Returns<Expression<Func<StubEntity, bool>>>(p => queryableData.Where(p));

    var context = new Mock<StubContext>();
    context.Setup(x => x.DbEntities).Returns(mockDbSet.Object);
    context.Setup(x => x.Set<StubEntity>()).Returns(mockDbSet.Object);

    _repository = new Repository<StubEntity>(context.Object);
}

I'm only testing the where clause into a test

[TestMethod]
public void Find_ReturnsProperEntity()
{
    var entity = _repository.Find(s => s.Id == 1);
    ....
}

where the Find method just call the where clause of the context.

public IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> predicate)
{
    return Context.Set<TEntity>().Where(predicate);
}
1 Answers
Related