Speed up creation of unit tests
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 Code 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 menu item. We are presented with the following:
Pressing the New Template button, we can define a whole template for a test fixture. You can use concrete types and implementations, but we are going to follow general NUnit conventions below:
Now if we want to use this template to create a unit test fixture, we can right-click a project and select. We are presented with the following dialog:
We can select our ‘Test Fixture’ here and additionally tick the 'Add to quicklist' so that the template is added quick access list for all C# projects and we have it the menu without selecting .
Clicking OK in the dialog 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 of the Templates Explorer window. Once again, we define a stub for a method, with
$NAME$ being a variable for the method name and
$END$ indicating where the caret is once the template expands.
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 define a live template with two parameters:
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 test and 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, and so on.