I am a big fan of making things easy for myself. When preparing the TDD Workshop for another round I found it increasingly tedious to type out every unit test function. Luckily, Visual Studio lets you create your own snippets, so I created one that would immediately generate something like this:
[Test]
public void GivenContext_WhenAction_ThenResult()
{
// Arrange
// Act
// Assert
}
How does it work I hear you say? It’s simpler than I expected:
- Create a .snippet file in
<documents>/Visual Studio 2017/Code Snippets/Visual C#/My Code Snippets(e.g. TDD.snippet) - Put the following XML content in the file:
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Unit test template</Title>
<Author>Daan Wissing</Author>
<Description>Insert Arrange/Act/Assert groups in unit test function</Description>
<Shortcut>unittest</Shortcut>
</Header>
<Snippet>
<Code Language="CSharp">
<![CDATA[[Test]
public void Given$context$_When$action$_Then$result$()
{
// Arrange
// Act
// Assert
}]]>
</Code>
<Declarations>
<Literal>
<ID>context</ID>
<Default>Context</Default>
<ToolTip>The context of this unit test</ToolTip>
</Literal>
<Literal>
<ID>action</ID>
<Default>Action</Default>
<ToolTip>The action that is tested</ToolTip>
</Literal>
<Literal>
<ID>result</ID>
<Default>Result</Default>
<ToolTip>The resulting state that will be asserted</ToolTip>
</Literal>
</Declarations>
</Snippet>
</CodeSnippet>
</CodeSnippets>
Done! Visual Studio will automatically pick up the new snippet file (maybe you need to restart). You can use the snippet by invoking IntelliSense (usually CTRL + SPACE), typing unittest and hitting TAB.
The highlighted lines are the meat of this snippet: the Code node contains what to actually insert in the editor. Most of the rest is some administration, but some extra fun is the Declarations node. In this snippet I have to fill in three important pieces of information of the unit test (the context, the action tested and the expectation) because these will change for every unit test.
Try it out yourself!