From time to time I find myself writing the same code – a task I find boring, tedious and error prone(I’m not talking about code duplication – which should be eliminated as the evil it is) as the lazy developer that I am I prefer to let a tool perform these tasks for me.
Today I found myself writing unit tests on a new machine – since all unit tests start the same way I’ve decided to create a Live Template to speed up my work.
Since I prefer to get to step #3 as soon as I can I usually create a Live Template to handle steps 1 & 2:
It’s right there under the “Resharper” menu:
Now choose the Live Template tab and press New Template button
A new page will appear in Visual Studio.
Give your nee template a shortcut, description and decide where it would be applicable.
In this case I’ve decided to go with ntest for shortcut for a template that would only be available in C# where a type member is allowed.
Writing a template is as simple as writing the actual code – no prior knowledge is needed. Use the dollar sign ($) to declare variables.
I my case I want to make sure I follow the same naming convention for every test so I declare three variables by putting them between two dollar sign – no additional work required.
To finish it off I add $END$ to let Rehsarper know where I want my cursor to be after I’ve finished giving the variables valid values.
I’ve also marked Reformat and Shorten qualified references to make sure that the resulting code is clean & tidy.
And you’re ready to go – the new template was added to the machines templates and you can use Template Explorer to put it under category and share it with your team.
Now all I need to do is write ntest press tab and presto – I get the “test skeleton” and I can jump between the variables I’m declared using tab.
Once I’m done giving the test a proper name the cursor waits inside the test method so I write the actual test.
As simple as that!
Live template are a powerful tool. In this post I’ve only scratched the surface of their functionality.
If you’re interested in learning more I suggest you head to Resharper documentation.
As for me I’m going to add few more of those and get back to writing code.
Happy coding…
Labels: NUnit, Resharper, Unit tests