I\'m trying to mock DbContext and DbSet. This works for my previous unit tests, but problem occurs while my code was calling ToList method on DbSet second time.
Firs
I just wanted to added to Wiktor Zychla's answer my little part. If someone is looking for Async version of this mock (coming from this tutorial: http://msdn.microsoft.com/en-us/data/dn314429.aspx#async) then this is my modification to TestDbAsyncEnumerator class:
internal class TestDbAsyncEnumerator : IDbAsyncEnumerator
{
private readonly IEnumerator _inner;
public TestDbAsyncEnumerator(IEnumerator inner)
{
_inner = inner;
}
public TestDbAsyncEnumerator(Func> valueFunction)
{
_inner = valueFunction();
}
public void Dispose()
{
_inner.Dispose();
}
public Task MoveNextAsync(CancellationToken cancellationToken)
{
return Task.FromResult(_inner.MoveNext());
}
public T Current
{
get { return _inner.Current; }
}
object IDbAsyncEnumerator.Current
{
get { return Current; }
}
}
Then like Wiktor suggested you have to setup it with delegate so in case of async it would be like that:
mockSet.As>()
.Setup(m => m.GetAsyncEnumerator())
.Returns(new TestDbAsyncEnumerator(() => data.GetEnumerator()));
If someone wants source for that then here you go: https://github.com/kelostrada/EntityFrameworkWithMock.Test