2

I'm familiar with techniques used for testing controllers and business logic in ASP .NET MVC application.

Data access in our app is concentrated in special services which are loosely coupled, use interfaces and work with actual database through Entity Framework.

However, as DAL became increasingly more complex, hiding away database implementation details and providing application code with abstractions, we became concerned if we are able to test it by any means. Because it is already tightly bound to EF context, we don't plan to introduce yet another repository-style layer, however this also means we can't just unit-test it with fake data.

I'm wondering if it's possible to somehow mock or stub Entity Framework object context while being able to do simple operations like adding/deleting entities and making queries.

I'm also looking for opinion on whether it is a good idea at all (perhaps really bad), and if it isn't, some 'smart' data layer testing advice.

3
  • I think you should remove the asp.net-mvc tag. When you have a loosely coupled data-access-layer it does not matter what is on top of that. Commented Jun 7, 2011 at 8:42
  • @steenhulthin, you're so right. Commented Jun 7, 2011 at 8:47
  • Yes it is. Take a look at this article: bit.ly/bF7jL3. Commented Jun 7, 2011 at 9:22

1 Answer 1

11

Mocking / stubbing EF is partially possible if you use IObjectSet and custom interface for your derived ObjectContext instance and all your EF dependent code will access EF features only through these interfaces (context will be injected). Every other EF related features must be hidden in methods exposed on object context interface.

I discussed in several answers (for example here and here) that this really doesn't help because you don't test the real code. The very big problem is that once you mock / stub EF code you are replacing linq-to-entities with linq-to-objects. Another problem is that you are losing referential integrity for persisting entities. Because of that I believe that DAL, persistence and querying should be covered with integration tests using real EF with real DB.

Sign up to request clarification or add additional context in comments.

1 Comment

I agree 100%. It is easy to fall in to a trap of thinking that you are unit testing your logic (i.e. the expressions you're passing to the LINQ methods). However, since you're using a completely different LINQ provider in your unit tests, those expressions could be completely invalid at runtime.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.