Unit testing a .NET Standard 1.6 library

10k views Asked by At

I am having trouble finding up to date documentation on how to unit test a .NET Standard 1.6 class library (which can be referenced from a .NET Core project).

Here is what my project.json looks like for my library:

{
  "supports": {},
  "dependencies": {
    "Microsoft.NETCore.Portable.Compatibility": "1.0.1",
    "NETStandard.Library": "1.6.0",
    "Portable.BouncyCastle": "1.8.1.2"
  },
  "frameworks": {
    "netstandard1.6": {}
  }
}

Now the left over task is to be able to create some sort of a project that can do the unit testing. The goal is to use xUnit since it seems that this is what the .NET Core team is pushing.

I went ahead and created another .NET Portable library project that has a project.json that looks like this:

{
  "supports": {},
  "dependencies": {
    "Microsoft.NETCore.Portable.Compatibility": "1.0.1",
    "NETStandard.Library": "1.6.0",
    "xunit": "2.2.0-beta4-build3444",
    "xunit.runner.visualstudio": "2.1.0"
  },
  "frameworks": {
    "netstandard1.6": {

    }
  }
}

My test class within that project looks like this:

using USB.EnterpriseAutomation.Security.DotNetCore;
using Xunit;

namespace Security.DotNetCore.Test
{
    public class AesEncryptionHelperTests
    {
        [Fact]
        public void AesEncryptDecrypt()
        {
            var input = "Hello world!";
            var encrypted = AesEncryptionHelper.AesEncrypt(input);
            var decrypted = AesEncryptionHelper.AesDecrypt(encrypted);

            Assert.Equal(input, decrypted);
        }
    }
}

When I go ahead and build that project, the Test Explorer is not seeing any of my tests.

How do I go about creating a unit test that's able to test this library?

2

There are 2 answers

3
Nate Barbettini On BEST ANSWER

I currently have a working project using xunit 2.1.0 and dotnet-test-xunit 2.2.0-preview2-build1029.

This is my project.json for the unit test project:

{
  "dependencies": {
    "dotnet-test-xunit": "2.2.0-preview2-build1029",
    "Microsoft.NETCore.App": {
      "type": "platform",
      "version": "1.0.0"
    },
    "MyProject.Library": {
      "target": "project",
    },
    "xunit": "2.1.0"
  },
  "description": "Unit tests",
  "frameworks": {
    "netcoreapp1.0": {
      "imports": "dotnet"
    }
  },
  "testRunner": "xunit"
}

This works both on the command line (via dotnet test) and in the Visual Studio 2015 Test Explorer.

I think that dotnet-test-xunit is being deprecated, but I'm not sure. All of the above will likely change after project.json goes away, but this works today.

0
Brett Mathe On

I found the issue posted on xUnit's GitHub page here: https://github.com/xunit/xunit/issues/1032

As Brad Wilson explains, NETStandard libraries must be tested with either a dotnet core library or a full .Net Framework library.

In my case I made my unit test library a full "classic desktop" library and Test Explorer was able to run my tests.