Unit tests are indispensable, but they are also very verbose – every test fixture requires a properly decorated class, every test case – its own method. Also, you may find yourself typing
Assert.Equals far too many times.
Let’s see if we can shorten the time necessary to create unit tests by using ReSharper’s Live Templates. We are going to start by creating a File Template, which is a way for ReSharper to create a whole file at once. First, let’s open up the ReSharper | Live Templates menu item. We are presented with the following:
Pressing the New Template button (leftmost icon), we can define a whole template for a test fixture. You can use concrete types and implementations, but we are going to follow general xUnit conventions below:
Now if we want this template to appear in the quick context menu for file templates, we can right-click on a project and select Add | New from Template | More. We are presented with the following dialog box:
Selecting ‘Test Fixture’, we get ReSharper to add it to the quicklist for all C# projects. Now, if we open Add | New from Template once again, we will see the following:
Firing up this template creates the following file:
The attributes can, of course, be customized to your preferred unit testing framework.
Now, let’s take a look at test methods. Typically, these are
void methods with no parameters (parameterized tests being a ‘special case’) with the
Test attribute appended.
For this, we switch to the Live Templates tab. Once again, we simply define a stub for a method, with
$NAME being a variable for the method name and
$END$ indicating where the caret ends.
test inside our test fixture and pressing Tab yields us a new test method.
Another thing we can do is create a live template for
Assert.IsEqual(). This is also easy: we simply define a live template with two placeholders:
Both of these use the Constant Value macro. This isn’t necessary, but it prettifies the code and makes the template more understandable when there comes a time to actually use it.
So there you have it – with the Test Fixture file template and the
ae templates, you can quickly and easily generate test code stubs. Feel free to use the same approach for other test-related elements, such as generating test fixtures with setup/tear-down methods, using the file generation as a live template instead of a file template (remember, you can always move the class to a separate file), creating live templates for other types of asserts, etc. Good luck!