C# Code Snippet for Unit Tests

By | July 24, 2014

After coding unit tests the whole day, I decided to create a nice Visual Studio snippet which helps me to write the test method quicker. I usually structure my unit tests like this:

public void Validate_ReturnsFalse_WhenStringIsTooLong()
{
	// Arrange
	var expectedResult = false;
	var watheverMock = new Mock<IWathever>();

	// Act
	var validator = new Validator(watheverMock.Object);
	var result = validator.Validate("test...");

	// Assert
	Assert.IsTrue(result == expectedResult, "Returned validation result: {0}. Expected validation result: {1}", result, expectedResult); 
} 

The method name is separated in three parts: “FunctionUnderTest”_”ExpectedResult”_”UnderWhichCondition”. And the unit test logic is build based on the AAA (Arrange,Act,Assert) pattern.
So my snippet does the typing work for you. (You can download the snippet here)
You can import the snippet file through the “Code Snippet Manager” under “Tools”.
Here an example how you can use it:
VS Unit Test