Testing T4 templates using mock framework (MoQ)

Some time ago I wrote a post in which I talk about how you can do unit tests over your text templates using the GAX Host. In that example I used a very simple template which receives just a couple of string properties. But it becomes more complicated when you have properties which are complex types ok I know, most probably you’re thinking that can resolve that just creating your own mock objects and you’re right.

But the thing is that you can do that in a really easiest way using a mock framework. I will not speak here about mock frameworks so you can find a lot of posts about it. I’ll speak about MoQ which is a new mock framework developed by Clarius and other companies. You can know more about MoQ in the Daniel’s blog and in its Google code page.

In the following example what I did was create a simple text template which uses an IEntitySchema object to create something like a Business Entity, so here we got an issue because we need an instance of that IEntitySchema and, the way to get it using the classic TDD approach, is creating an explicit Mock object.

So here is when MoQ comes to the rescue, if you see the code snippet it has a call to new Mock<IEntitySchema>() which will creates a proxy of an IEntitySchema implementation. After that, I defined our expectations for each interface signature in where we want to test an interaction.

image

image

So, at that point we’re ready to perform the tests and make all the assertions, plus the really interesting thing, which is the verification of all our expectations. That basically means that, beside make the assertions over states, now we can check if some interactions was made or not (in other words if some method or some property in the interface has been called or not and if was called with certain parameters values and types or not).

I think that the test interactions are a really interesting thing to include in our classic Todd fixtures.

Download Sample Code

Enjoy.

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *