This post is part of the series 'MSTest v2'. Be sure to check out the rest of the blog posts of the series!
Unit testing is part of the development process. If you are not writing much unit tests now, I would recommend reading this post which explains how testing helps to deliver faster and with more confidence: How we approach testing VSTS to enable continuous delivery. In this series of posts, we'll see how to write tests using MS Test v2, the Microsoft's test framework.
In Visual Studio, create a new "Unit Test Project" project:
If you want to use the command line in .NET Core, you can use the following command:
dotnet new mstest
The template contains the references to the following NuGet packages:
The csproj file should contains the following lines:
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.5.0" />
<PackageReference Include="MSTest.TestAdapter" Version="1.2.0" />
<PackageReference Include="MSTest.TestFramework" Version="1.2.0" />
To create a test, you have to write a method with the attribute
[TestAttribute] in a class decorated with the
[TestClass] attribute. The
TestClass attribute may seem superfluous, but we'll see in another post its importance 😃 You can use the methods of the
Assert class to validate the behavior of the method under test.
public class MathTests
public void Test_Add()
var actual = MathHelper.Add(1, 1);
var expected = 2;
public class MathHelper
public static int Add(int a, int b) => a + b;
Note: The first argument of the
Assert.AreEqual method is the expected value. If you swap the 2 arguments the error message may be weird.
You'll find lots of assert methods in the classes
StringAssert. We'll cover then in one of the next posts. It's not mandatory to use the
AssertXXX classes. In fact a test fails when an exception is raised.
Assert throws exception with a formatted message containing the expected and actual values. By using them you will get readable error message in the test result.
Now, you can run the test directly in Visual Studio. Open the Test Explorer window (Ctrl+E, T)
Since Visual Studio 2017 Update 5, the tests of the solution are discovered in real time. But if the tests are not visible, building the solution should make them visible. Once the test are visible, click the "Run All" button:
After a short time, the result of the test run is visible:
By default the tests are grouped by output result, so you can quickly find failed tests.
If you are using .NET Core, you can run tests using the following command:
The full documentation of
dotnet test is available in the documentation.
You now have the basis to create and run unit tests written with MSTest v2. In the next posts, we'll explore the functionalities of MSTest v2 and Visual Studio. Stay tuned!