Unit testing with Entity Framework

I want to test my Entities that are built using Entity Framework. My concern is that using Entity Framework means directly working with data source. So any ideas how to unit testing Entity Framework based components?


Solution 1:

For Enity Framework 4, this looks promising: Testability and Entity Framework 4.0

Solution 2:

Apparently it's very hard. Eloquently put by Erik here - TDD and ADO.NET Entity Framework

Solution 3:

A cheap approach is to set up a database file with the same structure as your real database and set the connection string in your unit test config to point to that. The database doesn't need to have all of the tables that the real one has; just the ones the unit test needs.

A disadvantage is that you need to manage the state of the database so that unit tests don't impact each other or themselves during and between runs.

I know this approach works when both the real and unit testing DBs use SQL Express but I don't know about stubbing in a SqlExpress DB for a full SQL DB.

I realize this is technically integration testing, but it could be cheaper than refactoring your code or learning a mocking framework.

Example real connection string:

<add name="DrinksEntities" 
     connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient
     ;provider connection string=&quot;Data Source=localhost\sqlexpress;Initial Catalog=Drinks2;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework&quot;" 
     providerName="System.Data.EntityClient" />

Example unit testing connection string:

<add name="DrinksEntities" 
     connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient
     ;provider connection string=&quot;Data Source=.\SQLEXPRESS;attachdbfilename=|DataDirectory|\Inventory.mdf;Integrated Security=True;user instance=True;MultipleActiveResultSets=True;Application Name=EntityFramework&quot;" 
     providerName="System.Data.EntityClient" />

Solution 4:

You are going to want to use a Mocking Framework to retrieve mock values rather than hitting the real data. Here are a list of a few mocking frameworks and links to some screencasts to help you get started:

  • Rhino Mocks

  • Moq

Here are some screencasts on how to get started:

Solution 5:

I would like to share another input to this. I was able to test Entity Framework based components and application using TypeMock Isolator as well. However it is commercial.

Have a look at this post: Introducing Entity Framework Unit Testing with TypeMock Isolator