Search code examples
c#entity-frameworkunit-testingmockingdata-access-layer

Is there any reason to use Mock objects when unit testing an Entity Framework DAL?


From what I understand, Mocking is used to remove dependency of another service so that you can properly test the execution of business logic without having to worry about those other services working or not.

However, if what you are testing IS that particular service (i.e. Entity Framework), Implementation-style unit tests against a preset test database are really the only tests that will tell you anything useful.

Am I missing anything? Does mocking have any place in my testing of an Entity Framework DAL?


Solution

  • You are correct in your assertion about mocking:

    Mocking is used to remove dependency of another service so that you can properly test the execution of business logic without having to worry about those other services working or not.

    In my words: the idea behind unit testing is to test a single code path through a single method. When that method hands execution over to another object there is a dependency. When control passes to an unmocked dependency you are no longer unit testing, but are instead integration testing.

    Data access layer testing is typically an integration test. As you speculate you can utilize a predictable data set to ensure your DAL is returning results as expected. I would not expect a DAL to have any dependencies which would require mocking. Your testing that the values returned by your DAL match what you would expect given your dataset.

    All of the above said it is not your responsibility to test the Entity Framework. If you find yourself testing the way EF works and are not creating tests about your specific DAL implementation then you are writing the wrong tests. Put another way: you test your code, let someone else test theirs.

    Finally, three years ago I asked a similar question which elicited answers which greatly improved my understanding of testing. While not identical to your question I'd recommend reading through the responses.