Thursday, September 24, 2009

TestMethod Code Snippet

If you’ve ever written more than one test method for any of the test frameworks out there that uses attributes, you know how quickly you start hoping for a code snippet to create the body of the method for you. Actually, you start hoping for one if you are aware that code snippets do exist. What? Everyone knows about snippets, no? Well, I’m sorry, but no. Think what you will, most people I have worked with didn’t know about code snippets until I told them that they existed. But if you do know about code snippets, here’s how you would go about creating a test method snippet for MSTest.

First, you absolutely need to download Snippet Editor on CodePlex. It makes creating snippets a breeze. So just download it, extract the files and run the executable.

Press the New button and you can start creating your snippet. The first fields are pretty self-explanatory. Just name and describe the snippet and name yourself as the other. Pay attention to the shortcut field, this is what you will need to type in the code editor to activate your snippet. I used tm. You then need to select the language for your snippet (C# in this case) and the kind of code your snippet produces.  Member Declaration is the type needed in our case.

Next up is the code itself. Just type the code you wish to appear once the snippet is activated. This is the code I wrote for my test method snippet:

[TestMethod]
public void TestThat()
{
    // Arrange

    // Act

    // Assert
}

Almost done, just click the save button and place the snippet in your snippet folder (document\Visual Studio 2008\Code Snippets\Visual C#\My Code Snippets by default). You are now ready to test your brand new code snippet.

Fire up Visual Studio, create a new class (test class or not, it doesn’t matter), move the cursor inside the class definition and press tm followed by tab. You should see the code above appear in the code editor. This easy shortcut will save you tons of typing, but you can make it even more useful!

You can have the snippet turn the name of the method into an editable field when the code is inserted. This is very easy to achieve again using the Snippet Editor. Simply return to Snippet Editor, select the name of the method in the code field and click the plus button in the lower frame. You could give the field another id, default value or specify a tooltip, but none of this is necessary. Just save the snippet and try it again in the Visual Studio code editor. When the code appears, you will notice that TestThat is now an editable green field. Just type tm then tab, type the name of the method, press enter and there you have it, a brand new test method for a fraction of the keystroke cost!

No comments: