The boilerplate code for unit tests can be the longest part of writing tests and if it isn't the longest part, it is almost always the most boring part! I have created my own NUnit snippets to help save time and keystrokes, I am going to talk about these macros in this post.
Test Fixtures
NUnit test fixture nunitfixture NUnit test fixture in C# Danny Kendrick Expansion testfixturename testfixturename testfixturename
The key things from the snippet above are
- Shortcut - This element is how you will call the snippet in Visual Studio
- Literal section - These elements are describing any literal values that the user will specify once the snippet is generated.
- Code - This element is where the code that will be generated is placed. To specify where the literal values will be placed use the syntax $variable$ as shown in the snippet.
nunitfiture
Will turn into the code below, with the testfixturename text highlighted by Visual Studio for replacement by the user.
[TestFixture] public class testfixturename { [SetUp] public virtual void SetUp() { } }
Test Fixtures
The next snippet is used to generate the tests themselves with comments for arrange, act and assert (the three A's of unit testing).
NUnit test nunittest NUnit test method in C# Danny Kendrick Expansion outcome outcome outcome condition condition condition
This snippet will generate following code with outcome and condition highlighted by Visual Studio for replacement.
[Test] public void Should_outcome_When_condition() { // Arrange // Act // Assert }
Test Fixtures
The last snippet I am going to talk about in this post is one I use for testing that an argument null exception is thrown correctly. This is important for me as I don't believe that the object should be create-able unless it's prerequisites are met. But this snippet could easily be modified for any type of exception.
NUnit ArgumentNullException nunitargnull NUnit test method that throws ArgumentNullException in C# Danny Kendrick Expansion parameter parameter parameter
This snippet will generate following code with parameter highlighted by Visual Studio for replacement.
[Test, ExpectedException(typeof(ArgumentNullException), ExpectedMessage = "Value cannot be null.\r\nParameter name: parameter")] public void ShouldThrowAnExceptionWhenparameterIsNull() { // Act }
Summary
Hopefully the snippets described in this post can help speed up your unit test development creation times as they have done with mine. Leaving the important part of the tests for me to fill in. To read more about creating Visual Studio snippets there is heaps of information on MSDN.
No comments:
Post a Comment