【发布时间】:2020-01-29 16:17:04
【问题描述】:
背景:
我有一个库,它同时针对 .NET Standard 2.0 和 .NET Core(以及其他)。由于 .NET Standard 2.0 缺少 .NET Core/Framework 中存在的许多功能,我从 .NET Standard 2.0 版本中的许多成员那里抛出了PlatformNotSupportedException。
问题 1:
UnitTest 项目不能以 .NET Standard 为目标,因此在测试项目中,我将 .NET Core 2.0 用于 .NET Core 和 Standard 版本。
在库 .csproj 中,我需要手动更改目标:
library.csproj:
<PropertyGroup>
<!-- Compiles everything; for testing everything but .NET Standard 2.0 -->
<TargetFrameworks>net35;net40;net45;netcoreapp2.0;netstandard2.0;netstandard2.1</TargetFrameworks>
<!-- For testing .NET Standard 2.0: -->
<!--<TargetFrameworks>netstandard2.0</TargetFrameworks>-->
</PropertyGroup>
test.csproj:
<PropertyGroup>
<!-- now 'netcoreapp2.0' references either the .NET Core 2.0 or Standard 2.0 version depending on library.csproj -->
<TargetFrameworks>net35;net40;net45;netcoreapp2.0;netcoreapp3.0</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\library\library.csproj" />
</ItemGroup>
问题 2:
考虑到单元测试项目不能以 .NET Standard 为目标,此代码不起作用:
[Test]
public void TestSomethingThatIsNotAvailableInNetStandard20()
{
TestDelegate testCode = () => ...;
#if NETSTANDARD2_0 // This is never true
Assert.Throws<PlatformNotSupportedException>(testCode);
#else
Assert.DoesNotThrow(testCode);
#endif
}
相反,现在我使用这样的东西:
[Test]
public void TestSomethingThatIsNotAvailableInNetStandard20()
{
TestDelegate testCode = () => ...;
#if NETCOREAPP2_0 // .NET Core 2.0 OR .NET Standard 2.0
if (IsNetStandard20)
Assert.Throws<PlatformNotSupportedException>(testCode);
else
Assert.DoesNotThrow(testCode);
#else // all other targets
Assert.DoesNotThrow(testCode);
#endif
}
...
// yikes... :/
public static bool IsNetStandard20 => typeof(SomeTypeFromMyLib).Assembly.GetReferencedAssemblies()
.Any(an => an.Name == "netstandard" && an.Version == new Version(2, 0, 0, 0));
问题:
有没有办法在不更改 .csproj 文件的情况下测试 .NET Standard 2.0 版本(如果可能,可以去掉 IsNetStandard20 属性)?
免责声明:
我知道通常发布 .NET Standard 2.0 版本来支持 .NET Core 应用程序就足够了,但不幸的是,它缺少 .NET Core 2.0 所具有的许多功能(尽管这些功能包含在 .NET Standard 2.1 中,所以不需要单独的 .NET Core 3.0 版本)。
【问题讨论】:
-
除非有人可以详细说明如何以另一种方式实现您正在寻找的东西,否则请接受我的回答。 Afaik 今天没有其他方法可以解决您的问题。
-
我赞成你的回答,但它不能解决我的问题。看来“没有办法”比“没有办法”更正确。
标签: c# unit-testing .net-core nunit .net-standard