Visual Studio Code Snippets
Handy for Unit Tests – and Much More!
I recently found myself having to type some code in repeatedly while unit testing. This sort of thing:
You can see here that I’ve been using Roy Osherove’s naming convention, which I like a lot. I’m also using the AAA (arrange-act-assert) layout for the test code, which I like to comment for increased readability. Although I’ve done something similar many times, I must have seen something about Code Snippets recently as I thought it might be a good idea to give them a try.
Code snippets are a part of Visual Studio (2008 certainly, not sure about before that). They are little code templates that you can get via intellisense, for example when you type ‘if’:
and then hit ‘Tab’ twice, you get the ‘If template’, with the section highlighted ready for you to put your condition in:
As it turns out, Vis Studio doesn’t ship with a snippet editor, but there is a very good open source one on CodePlexwhich is linked to from MSDN. Using this, I can put in my unit test template, and define the ‘tokens’ that I want to replace (in this case, ‘method name’, ‘state under test’ & ‘expected behaviour’):
I’ve also put in the $selected$$end$ bit, which defines where the cursor goes when you’re done. You can see in this one that I’ve put in a #region for the method name as well – the snipped editor’s smart enough to realise this is the same as the one in the method name. Here I’ve defined the shortcut as ‘ter’ (for ‘Test with Region’), because I don’t like typing.
So save that, and Bob’s your uncle! Go back into Visual Studio, type ‘ter’ (tab-tab), and as if by magic, you very own unit test template appears, awaiting your input!
It’s the type of thing you wish you’d found out about years ago, and I’m sure over the next few days I’ll make about a hundred of these things for increasingly pointless bits of code. But it’s another productivity increase, and they all add up, so if I find a few more of these I’ll be able to write a day’s worth of code in about two keystrokes!
Now I wonder what else Visual Studio does that I don’t know about..