10 March 2012

Automate Entity Framework 4.x mocking using T4 templates - part 2

  In my previous post I described how to use T4 templates to customize the Entity Framework(EF) code generation in order to introduce EF testability. My test code sample showed a very simple way to inject data and test the business logic without using a physical database. However the code that injects the test data could do with a bit of automation itself.

  I need a helper class that :
  • allows me to easily add test data;
  • can create a simple stub for the IDbContext interface – similar with the initial test example;
  • can create a mock with some default behaviour already specified - e.g. I need to check that the IDbContext.Delete method is called exactly 3 times for a specific entity but I don’t care about the IDbContext.Add method.
  By using another T4 template the helper class is now created. This allows me to refactor the initial test into:

  I still have some noise from the data creation code. In a lot of cases I don’t really care about the content of my data, except for a couple of fields or foreign keys. Ideally I should be able to generate objects with default data and set only the bits I need. Fortunately I can use an excellent library called AutoFixture to accomplish all this. AutoFixture will populate any new class instances with sensible defaults and supports a lot of customisations that allow you to skip properties and override default values. It is easily extensible and it has become an indispensible tool for all my unit testing needs.
  Using AutoFixture my test is now a lot shorter:

  At this point unit testing Entity Framework is production ready and the helper class described here should allow me to easily create test data, freeing me from the physical database dependency.

No comments: