简体   繁体   中英

Is it possible to build .NET Standard + .NET Core class/library to .NET Standard only?

I have a class/library project using .NET Standard 2.0, and I want to add unit testing to it inside the project directly (so it's easier to spot and more coupled). But, because every test framework needs to specific platform, I have no choice but to add another framework such as .NET Core.

I need to build this project to .NET Standard only because I need to use it in another project (Unity project, where the framework chosen is .NET Standard 2.0).

Can I add .NET Core to the project so that I can use a unit testing framework, but build the final dll using .NET Standard only?

Or should I just give up and do it with another project referencing this project instead? Because it's more comfortable if the unit test is embedded within the project directly as to not forget to update the unit test when something change.

Ok, I think I figured out how to do this for my specific needs without breaking anything.

First, add .NET Core to project dependencies and add the test framework (XUnit, NUnit, MSTest, etc.). Then, add the test as usual but put a guard on the unit test functions and includes.

For example (using XUnit), we want to run or enable unit test in the debug build only :

#if DEBUG
using Xunit;
#endif

and

#if DEBUG
    [Fact]
    public void Test() {
        Assert.True(something);
    }
#endif

Then, on the .csproj file, add a guard for the dependency :

<ItemGroup>
  <PackageReference Condition="'$(Configuration)'=='Debug'" Include="Microsoft.NET.Test.Sdk" Version="15.9.0" />
  <PackageReference Condition="'$(Configuration)'=='Debug'" Include="xunit" Version="2.4.1" />
  <PackageReference Condition="'$(Configuration)'=='Debug'" Include="xunit.runner.visualstudio" Version="2.4.1" />
</ItemGroup>

This will ensure that it will not link to the specific test framework on the release build.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM