Writing unit tests is important for making robust application code. In this article I will explain why naming conventions are important, show an example with some practical comments and share my Visual Studio snippet (big time-saver).
When writing a unit test it is important to give a good descriptive name for your class and test methods, using a naming convention. The convention that I personally like:
- Name the class in the form of 'WhenUsing$ClassName$', where $ClassName$ is the application class I want to write tests for.
- Name the test methods in the form of 'Given_$StateUnderTest$_Expect_$ExpectedBehavior$', where state and behaviour specify the start and end condition of the test.
This naming convention results in very readable sentences in fail messages and a nice structure in Visual Studio:
Example unit test for testing Free Shipping method of PostalService class:
public class WhenUsingPostalService
public void Given_OrderAbove50_Expect_FreeShipping()
PostalService postalService = new PostalService();
bool freeShipping = postalService.FreeShipping(55.0);
There are few things I want to point out:
- I am using FluentAssertions library (line 1, available as NuGet package). This helps me to write asserts in a human readable way on line 17: freeShipping.Should().BeTrue()
- I am using xUnit (line 2, available as NuGet package) as testing framework here, so I can annotate my tests with [Fact] on line 7.
- I try to follow the convention Arrange + Act + Assert to structure my tests.
Due to the use of conventions and structure, unit test code are looking much alike. So, this is a great opportunity to create a reusable Code Snippet to save time. With a Code Snippet you configure a shortcut code and when pressing tabs two times to replace it with a complete block of code.
My snippet is using the shortcut xfact and works like this:
You can download the Visual Studio snippet for xUnit test in my Github repository. You can use Code Snippets Manager to import into Visual Studio.