DbSet mock, no results while calling ToList secondly

后端 未结 4 1496
情深已故
情深已故 2020-12-15 06:29

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

4条回答
  •  萌比男神i
    2020-12-15 06:33

    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

提交回复
热议问题