Jose Escrich

Extensibility Thoughts

May 2007 - Posts

Testing T4 templates using the GAX host

Download Sample Package


I guess that there are not a best approach to do the tests without a built in support in the T4 template host. Nevertheless in the Web Service Software Factory we did a very first approach of how you could write test units for t4 templates.

Suppose that we have a template which the output is a simple class, in the following example I did a simple package which contains a T4 template called Programs.cs.t4 so, the idea is, run the transformation and then try to compile the class to get its Type in order to make asserts using reflection.

In the attached sample fixture it has an ExecuteTemplate helper method which has the logic to run the transformation and then try to compile it. (considering that the output is a .cs class, if not, it could return an XmlDocument in case that the transformation results in an xml file).



In the next picture you've the TestMethod which runs the transformation, gets the returned type and then perform different asserts over it.


Notice that you should have created a link to the T4 template file and set the *Copy to Output* property as "Copy if newer" as showing in the following image, this is an important thing because the TestMethod is marked with the DeploymentItemAttribute in order to have the t4 file in the test context. Also you have to reference the Microsoft.Practices.RecipeFramework.VisualStudio.Library and Microsoft.VisualStudio.TextTemplating assemblies which are located in the PublicAssemblies folder.




Download Sample Package

More Posts