我有一个简单的dotnet核心类库和一个XUnit测试方法:

TestLib.csproj:
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.SDK" Version="15.9.0" />
    <PackageReference Include="xunit" Version="2.4.1" />
    <PackageReference Include="xunit.runner.console" Version="2.4.1">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="xunit.runner.visualstudio" Version="2.4.1">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="xunit.runners" Version="2.0.0" />
  </ItemGroup>

</Project>

BasicTest.cs:
using Xunit;

namespace TestLib
{
    public class BasicTest
    {
        [Fact(DisplayName = "Basic unit test")]
        [Trait("Category", "unit")]
        public void TestStringHelper()
        {
            var sut = "sut";
            var verify = "sut";

            Assert.Equal(sut, verify);
        }
    }
}

如果我在CLI中输入项目并输入dotnet build,项目就会生成。如果我输入dotnet test,我得到这个:

C:\git\Testing\TestLib> dotnet test
C:\git\Testing\TestLib\TestLib.csproj : warning NU1701: Package 'xunit.runner.visualstudio 2.4.1' 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.
Build started, please wait...
C:\git\Testing\TestLib\TestLib.csproj : warning NU1701: Package 'xunit.runner.visualstudio 2.4.1' 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.
Build completed.

Test run for C:\git\Testing\TestLib\bin\Debug\netstandard2.0\TestLib.dll(.NETStandard,Version=v2.0)
Microsoft (R) Test Execution Command Line Tool Version 16.0.0-preview-20181205-02
Copyright (c) Microsoft Corporation.  All rights reserved.

Starting test execution, please wait...
Unable to find C:\git\Testing\TestLib\bin\Debug\netstandard2.0\testhost.dll. Please publish your test project and retry.

Test Run Aborted.

我需要更改哪些内容才能运行测试?

如果有帮助的话,VS Code也没有在它的测试资源管理器中显示测试。


当前回答

这也可能是由于无意中试图运行一个非测试项目造成的,这通常发生在你的测试文件过滤器太宽的时候。

其他回答

我正在构建一个netcoreapp2.2测试项目,然后试图从bin文件夹中运行dotnet vstest。我注意到微软测试dll来自:

<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />

没有输出到我的bin文件夹。而不是只是构建,我运行了一个发布,而不是在输出文件夹中包含必要的dll,然后我就可以从那里运行dotnet vstest。

我使用的是。net核心框架6.0,为了解决这个问题,我不得不将Microsoft.NET.Test.Sdk从17.1.0版本降级到16.5.0版本。

从nuget包管理器安装Microsoft.NET.Test.Sdk包解决了我的问题。

对我来说,这是个愚蠢的错误。我也在我的源项目中引用xunit(不仅仅是在我的测试项目中)

删除源项目中的xunit依赖项解决了这个问题。

重新启动Visual Studio并重新构建。在切换分支后,Visual Studio有时似乎会感到困惑。