I don't want Entity Framework code counted in code coverage.

Problem:

The code generated by the Entity Framework is distorting my code coverage numbers.

Solution:

Add a Code Generation Item and add the [DebuggerNonUserCode] attribute to the generated classes.

Explanation:

As I described in a previous post here the [DebuggerNonUserCode] hides the code from code coverage results.  I am a huge fan of code coverage however; I do not see the point in testing generated code especially when most of it is just value objects.

Entity Framework uses T4 Text Templates to generate the typed ObjectContext and EntityObject derived entity classes used in your code.  If the code generated does not fit your needs you can add a Code Generation Item to your project and the Entity Framework will use your custom T4 Text Template to generate the classes.

Adding a new Code Generation Item is very easy.  Simply open your .edmx file and right click on the design surface and select Add Code Generation Item… from the context menu. 

When the Add New Item dialog is presented select the Code section under your language of choice.  You will be presented two generator templates to choose from.  The ADO.NET EntityObject Generator template generates the same code as the default code generated by the Entity Framework Designer.  In solution explorer you will see a new file with a .tt extension.  This file will create a .cs (or .vb) file which appears under the .tt file in Solution Explorer.

All we have to do now is modify the template by adding a using statement for System.Diagnostics and add the [DebuggerNonUserCode] attribute on all the partial classes in the template (there are 3). With the template in your solution all the Entity Framework code will be generated with the [DebuggerNonUserCode] attribute and removed from the code coverage calculations.

 

You can download a copy of the T4 Template below.

Model1.tt (45.02 kb)

Comments are closed