We already introduced the Template Producer in a previous post with a small example showing how to generate a DGML graph from a CodeFluent Entities model. This post is another example to remind you how easy it is to generate text files using the Template Producer whilst accessing the inferred meta-model.
Let’s say we’d like to generate a skeleton for our unit tests. By skeleton I mean a vb or csharp file by entity that will contain test methods ready to be implemented.
Assuming we are writing a pretty simple bank application. Our model has an “Account” entity and 3 methods (to deposit, withdraw, and transfer funds) as follow:
Supposing we’re using Nunit as unit-testing framework, let’s create our template to be used by the Template Producer:
[%@ namespace name="System"%] [%@ namespace name="CodeFluent.Model"%] [%@ namespace name="CodeFluent.Model.Code"%] [%@ template enumerable='Producer.Project.Entities' enumerableItemName="entity" enumerableTargetPathFunc='Path.Combine(Path.GetDirectoryName(TargetPath), String.Format("{0}Tests", entity.ClrFullTypeName)) + ".cs"' %] using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; namespace [%= entity.Namespace %] { [TestFixture] public class [%= String.Format("{0}Tests", entity.Name) %] { [SetUp] public void Init() { /* ... */ } [TearDown] public void Cleanup() { /* ... */ } [% foreach(Method m in entity.Methods) { if (!m.Enabled) continue; %] [Test] [%= String.Format("public void {0}Test()", m.Name) %] { /* ... */ } [% } %] } }
Basically, what the template does is that it iterates through all entities of the project as well as each method to write a file by entity containing a test class with all test methods.
- Create a class library project called Bank.UnitTests to store all your unit tests and add it a reference to Nunit framework.
- Add a Template Producer and set the Source directory to your Templates folder created earlier and the Target directory to the Bank.UnitTests project.
The Template Producer instance will execute all templates placed in the Templates directory, and place output files in the Bank.UnitTests project directory.
Building your model should produce one file called Bank.AccountTests.cs with all the test methods ready to be implemented:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; namespace Bank { [TestFixture] public class AccountTests { [SetUp] public void Init() { /* ... */ } [TearDown] public void Cleanup() { /* ... */ } [Test] public void DepositTest() { /* ... */ } [Test] public void WithdrawTest() { /* ... */ } [Test] public void TransferFundsTest() { /* ... */ } } }
As you can see, this short and simple example gives you an idea of what it is possible to do by taking advantage of the meta model using the Template Producer.
Want to know more? You’ll find more information on the Template Producer here.
Cheers,
Thibault NESTOR
