none
Mocking DbContext and Repository methods with AsNoTracking extension RRS feed

  • Question

  • Hi all,

    I have a basic Entity Framework code first generated DbContext and a repository with methods which I am trying to test with moq. The method body looks like this: "return _products.AsNoTracking().OrderBy(x => x.Name).ToList(); ". My tests fail every time, when AsNoTracking() extension is included, since it returns null. Yet, if AsNoTracking() extension is removed tests pass straight away. So far I could not find any way to resolve this issue. Is it even possible? The only thing I managed to find online, was creating a custom extension method for AsNoTracking(), which would keep it enabled by default, and disable it when user passes a parameter in during testing. But this is not a real solution, since it still does not allow you to test whole method, and essentially removes AsNoTracking(), during test (cheating).

    Therefore, let me refocus my question.

    Can a method with AsNoTracking() extension in it be tested? If yes, then how? If no, than what would be the best practice to deal with this issue.

    Thank you 


    Wednesday, March 1, 2017 9:04 PM

All replies

  • Hi BenjaminHauer,

    Since DbSet<Product> is indeed a DbQuery, which DbSet is deriving from DbQuery, it tries to invoke the 'real' (non-mocked) AsNoTracking() method which rightfully returns null.

    Please mock the AsNoTracking() method as well:

    mockSet.Setup(x => x.AsNoTracking()).Returns(mockSet.Object);

    For more information, please refer to:

    http://stackoverflow.com/questions/27038253/mock-asnotracking-entity-framework

    Best regards,

    Cole Wu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, March 3, 2017 7:47 AM
    Moderator
  • Thank you for your reply. Unfortunately for me this setup does not work, I saw stackoverflow post you mentioned. In the same post it is explained that AsNoTracking() is an extension method and therefore just syntactic sugar. Or have you actually tried it and it worked for you?
    Friday, March 3, 2017 7:50 PM