Migrating from MSTest to xUnit.net

In order to assist in migrating unit tests from MSTest V2 to xUnit.net, it can often be helpful to have unit tests from MSTest and xUnit.net side by side. Tests can then be migrated gradually without breaking the compiler nor the test results in most cases.

Note: The version numbers in this example may change over time. Please always use the latest versions of packages that are available.

Step 1: Add NuGet packages

Remove packages: MSTest.TestAdapter, and MSTest.TestFramework.

Install packages: xunit, xunit.runner.visualstudio, and xunit.MSTest.

Example:

 <ItemGroup>
   <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.1" />
-  <PackageReference Include="MSTest.TestAdapter" Version="2.1.0" />
-  <PackageReference Include="MSTest.TestFramework" Version="2.1.0" />
+  <PackageReference Include="xunit" Version="2.4.1" />
+  <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" />
+  <PackageReference Include="xunit.MSTest" Version="1.0.3" />
   <PackageReference Include="coverlet.collector" Version="1.3.0" />
 </ItemGroup>

The xunit package replaces MSTest.TestFramework, and the xunit.runner.visualstudio package replaces MSTest.TestAdapter. The xunit.MSTest package provides a backward compatibility layer that makes porting your tests easier, and will be removed after all your tests have been ported.

Step 2: Apply changes

Apply all suggested changes from compiler warnings. Example:

 using Microsoft.VisualStudio.TestTools.UnitTesting;

 // Warning CS0618 'TestClassAttribute' is obsolete: 'Remove this attribute.'
-[TestClass]
 public class UnitTest1
 {
     // Warning CS0618 'TestMethodAttribute' is obsolete: 'Use Fact instead.'
-    [TestMethod]
+    [Fact]
     public void TestMethod1()
     {
         // Warning CS0618 'Assert.IsTrue(bool, string)' is obsolete: 'Use True instead.'
-        Assert.IsTrue(true);
+        Assert.True(true);
     }
 }

Some of these text replacements can be automated with the command line tool from XUnitConverter.

Step 3: Switch to xUnit.net

Change import statements from MSTest to xUnit.net. Example:

-using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Xunit;

 public class UnitTest1
 {

Step 4: Remove NuGet package

Remove backwards compatibility NuGet package. Example:

 <ItemGroup>
   <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.1" />
   <PackageReference Include="xunit" Version="2.4.1" />
   <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" />
-  <PackageReference Include="xunit.MSTest" Version="1.0.3" />
   <PackageReference Include="coverlet.collector" Version="1.3.0" />
 </ItemGroup>
Copyright © .NET Foundation. Contributions welcomed at https://github.com/xunit/xunit/tree/gh-pages.