none
Entity Framework Testing with a mocking framework example RRS feed

  • Question

  • Hello,
    I was trying to implement the example from msdn to make my own tests using entity framework and Moq - http://msdn.microsoft.com/en-us/data/dn314429#async

    The things is - it works, but I found a problem and a solution for that also so I wanted to share (and maybe ask if the example shouldn't  be corrected in some way?). You can find my implementation on github: https://github.com/kelostrada/EntityFrameworkWithMock.Test

    The problem I had was with using mocked dbSets - when I used them directly to call a method like `ToList()` then the enumerator was being used every time in the same state resulting in something Like this:

    var a = mockContext.Blogs.ToList(); // this list has 3 elements
    var b = mockContext.Blogs.ToList(); // this one has 0 elements

    I solved it by passing a delegate to the method which called the enumerator every time so it was in a reseted state.

    dbSetMock.As<IDbAsyncEnumerable<DbUser>>()
                    .Setup(m => m.GetAsyncEnumerator())
                    .Returns(new TestDbAsyncEnumerator<DbUser>(userData.GetEnumerator));
    
    dbSetMock.As<IQueryable<DbUser>>().Setup(m => m.GetEnumerator()).Returns(userData.GetEnumerator);

    Can you look at this, and tell me if my solution is all right? In my opinion it should be mentioned somewhere on the tutorial page, I would appreciate any opinion on this.


    • Moved by Fred BaoModerator Tuesday, November 4, 2014 6:40 AM Move to a more appropriate forum
    Monday, November 3, 2014 10:44 AM

Answers

  • Hello Kelostrada,

    With your provide information, I made a test from that article and download your project and find the root reason is this change:

    mockSet.As<IQueryable<Blog>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());

    To

    mockSet.As<IQueryable<Blog>>().Setup(m => m.GetEnumerator()).Returns(() => data.GetEnumerator());

    The first one seems to the two queries use the same enumerator and after the first query, the enumerator would stay at the end of the list so that it return 0 element. The second one would create a new one for each query. However, I am not sure about this, you could confirm with the author of the Moq.dll to ensure this behavior.

    Regards.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Tuesday, November 4, 2014 7:34 AM
    Moderator