Unit Tests and .Net Standard

//Unit Tests and .Net Standard

Unit Tests and .Net Standard

The other day I created a .Net standard assembly, and needed some unit tests for it. For the purpose of this example, Let’s say that my Core dll consists of the class

public class Calculator
{
    public int Add(int x, int y) => x + y;
}

Since my Core assembly is in .Net Standard, I also created my Tests assembly in .Net Standard

Then I added NuGet references to MSTest.TestFramework and MSTest.TestAdapter.

I then created the test class

[TestClass]
public class CalculatorTests
{
    [DataTestMethod]
    [DataRow(1, 2, 3)]
    [DataRow(5, 5, 10)]
    [DataRow(-2, 2, 0)]
    public void TestCalculate(int x, int y, int expected)
    {
        var result = new Calculator().Add(x, y);
        Assert.AreEqual(expected, result);
    }
}

Now, Using the Test Explorer, I wanted to run the tests.

However, nothing happens!
In the Output Window, the following warnings are written:

[2018-12-16 08:02:13 Informational] ------ Run test started ------
[2018-12-16 08:02:14 Warning] [MSTest][Discovery][D:\proj\mstest-standard\Tests\bin\Debug\netstandard2.0\Tests.dll] MSTestAdapter failed to discover tests in class 'Tests.CalculatorTests' of assembly 'D:\proj\mstest-standard\Tests\bin\Debug\netstandard2.0\Tests.dll' because Could not load file or assembly 'Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified..
[2018-12-16 08:02:14 Warning] No test matches the given testcase filter `FullyQualifiedName=Tests.CalculatorTests.TestCalculate` in D:\proj\mstest-standard\Tests\bin\Debug\netstandard2.0\Tests.dll
[2018-12-16 08:02:14 Informational] ========== Run test finished: 0 run (0:00:01.3389902) ==========

There is also another clue as to what is happening, a warning in the MSTest.TestAdapter reference:

The full warning reads

Package 'MSTest.TestAdapter 1.4.0' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETStandard,Version=v2.0'. This package may not be fully compatible with your project.

It turns out that the problem is that test projects cannot target .Net Standard, but must target either .Net Framework or .Net Core.

The solution lies in targeting .Net Framework instead of .Net Standard when creating the test project:

Adding the same NuGet references and the same test class, the tests can now be executed successfully:

This limitation does not only apply to MSTest, but to all other unit testing frameworks, such as xUnit and NUnit.

Happy Testing!

By | 2018-12-16T07:40:21+00:00 December 18th, 2018|Uncategorized|0 Comments

About the Author:

I'm passionate about software development. Can't help it.

Leave A Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.