dotnet testdotnet test

本文适用于: ✔️ .NET Core 2.1 SDK 及更高版本This article applies to: ✔️ .NET Core 2.1 SDK and later versions

“属性”Name

dotnet test - 用于执行单元测试的 .NET 测试驱动程序。dotnet test - .NET test driver used to execute unit tests.

摘要Synopsis

dotnet test [<PROJECT> | <SOLUTION> | <DIRECTORY> | <DLL>]
    [-a|--test-adapter-path <ADAPTER_PATH>] [--blame] [--blame-crash]
    [--blame-crash-dump-type <DUMP_TYPE>] [--blame-crash-collect-always]
    [--blame-hang] [--blame-hang-dump-type <DUMP_TYPE>]
    [--blame-hang-timeout <TIMESPAN>]
    [-c|--configuration <CONFIGURATION>]
    [--collect <DATA_COLLECTOR_NAME>]
    [-d|--diag <LOG_FILE>] [-f|--framework <FRAMEWORK>]
    [--filter <EXPRESSION>] [--interactive]
    [-l|--logger <LOGGER>] [--no-build]
    [--nologo] [--no-restore] [-o|--output <OUTPUT_DIRECTORY>]
    [-r|--results-directory <RESULTS_DIR>] [--runtime <RUNTIME_IDENTIFIER>]
    [-s|--settings <SETTINGS_FILE>] [-t|--list-tests]
    [-v|--verbosity <LEVEL>] [[--] <RunSettings arguments>]

dotnet test -h|--help

描述Description

dotnet test 命令用于在给定的解决方案中执行单元测试。The dotnet test command is used to execute unit tests in a given solution. dotnet test 命令生成解决方案,并为解决方案中的每个测试项目运行测试主机应用程序。The dotnet test command builds the solution and runs a test host application for each test project in the solution. 测试主机使用测试框架(例如,MSTest、NUnit 或 xUnit)在给定项目中执行测试,并报告每个测试成功与否。The test host executes tests in the given project using a test framework, for example: MSTest, NUnit, or xUnit, and reports the success or failure of each test. 如果所有测试均成功,测试运行程序将返回 0 作为退出代码;否则将返回 1。If all tests are successful, the test runner returns 0 as an exit code; otherwise if any test fails, it returns 1.

对于多目标项目,将为每个目标框架运行测试。For multi-targeted projects, tests are run for each targeted framework. 测试主机和单元测试框架打包为 NuGet 包,并还原为项目的普通依赖项。The test host and the unit test framework are packaged as NuGet packages and are restored as ordinary dependencies for the project.

测试项目使用普通 <PackageReference> 元素指定测试运行程序,如下方示例项目文件所示:Test projects specify the test runner using an ordinary <PackageReference> element, as seen in the following sample project file:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.1" />
    <PackageReference Include="xunit" Version="2.4.1" />
    <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" />
  </ItemGroup>

</Project>

如果 Microsoft.NET.Test.Sdk 是测试主机,则 xunit 是测试框架。Where Microsoft.NET.Test.Sdk is the test host, xunit is the test framework. 另外,xunit.runner.visualstudio 是测试适配器,可便于 xUnit 框架与测试主机一起运行。And xunit.runner.visualstudio is a test adapter, which allows the xUnit framework to work with the test host.

隐式还原Implicit restore

无需运行 dotnet restore,因为它由所有需要还原的命令隐式运行,如 dotnet newdotnet builddotnet rundotnet testdotnet publishdotnet packYou don't have to run dotnet restore because it's run implicitly by all commands that require a restore to occur, such as dotnet new, dotnet build, dotnet run, dotnet test, dotnet publish, and dotnet pack. 若要禁用隐式还原,请使用 --no-restore 选项。To disable implicit restore, use the --no-restore option.

在执行显式还原有意义的某些情况下,例如 Azure DevOps Services 中的持续集成生成中,或在需要显式控制还原发生时间的生成系统中,dotnet restore 命令仍然有用。The dotnet restore command is still useful in certain scenarios where explicitly restoring makes sense, such as continuous integration builds in Azure DevOps Services or in build systems that need to explicitly control when the restore occurs.

有关如何使用 NuGet 源的信息,请参阅 dotnet restore 文档For information about how to manage NuGet feeds, see the dotnet restore documentation.

自变量Arguments

  • PROJECT | SOLUTION | DIRECTORY | DLL

    • 指向测试项目的路径。Path to the test project.
    • 解决方案的路径。Path to the solution.
    • 包含项目或解决方案的目录的路径。Path to a directory that contains a project or a solution.
    • 测试项目 .dll 文件的路径。Path to a test project .dll file.

    如果未指定,则会在当前目录中搜索项目或解决方案。If not specified, it searches for a project or a solution in the current directory.

选项Options

  • -a|--test-adapter-path <ADAPTER_PATH>

    要在其中搜索其他测试适配器的目录的路径。Path to a directory to be searched for additional test adapters. 只检查后缀为 .TestAdapter.dll 的 .dll 文件。Only .dll files with suffix .TestAdapter.dll are inspected. 如果未指定,则会搜索测试 .dll 的目录。If not specified, the directory of the test .dll is searched.

  • --blame

    在意见模式中运行测试。Runs the tests in blame mode. 此选项有助于隔离导致测试主机出现故障的有问题的测试。This option is helpful in isolating problematic tests that cause the test host to crash. 检测到故障时,它会在 TestResults/<Guid>/<Guid>_Sequence.xml 中创建一个序列文件,用于捕获在出现故障之前运行的测试的顺序。When a crash is detected, it creates a sequence file in TestResults/<Guid>/<Guid>_Sequence.xml that captures the order of tests that were run before the crash.

  • --blame-crash (自 .NET 5.0 预览版 SDK 起可用)--blame-crash (Available since .NET 5.0 preview SDK)

    在追责模式下运行测试,并在测试主机意外退出时收集故障转储。Runs the tests in blame mode and collects a crash dump when the test host exits unexpectedly. 此选项仅可用于 Windows。This option is only supported on Windows. 包含 procdump.exe 和 procdump64.exe 的目录必须位于 PATH 或 PROCDUMP_PATH 环境变量中。A directory that contains procdump.exe and procdump64.exe must be in the PATH or PROCDUMP_PATH environment variable. 下载工具Download the tools. 意味着 --blameImplies --blame.

  • --blame-crash-dump-type <DUMP_TYPE> (自 .NET 5.0 预览版 SDK 起可用)--blame-crash-dump-type <DUMP_TYPE> (Available since .NET 5.0 preview SDK)

    要收集的故障转储的类型。The type of crash dump to be collected. 意味着 --blame-crashImplies --blame-crash.

  • --blame-crash-collect-always (自 .NET 5.0 预览版 SDK 起可用)--blame-crash-collect-always (Available since .NET 5.0 preview SDK)

    在预期和意外的测试主机退出时收集故障转储。Collects a crash dump on expected as well as unexpected test host exit.

  • --blame-hang (自 .NET 5.0 预览版 SDK 起可用)--blame-hang (Available since .NET 5.0 preview SDK)

    在追责模式下运行测试,并在测试超过给定超时时长时收集挂起转储。Run the tests in blame mode and collects a hang dump when a test exceeds the given timeout.

  • --blame-hang-dump-type <DUMP_TYPE> (自 .NET 5.0 预览版 SDK 起可用)--blame-hang-dump-type <DUMP_TYPE> (Available since .NET 5.0 preview SDK)

    要收集的故障转储的类型。The type of crash dump to be collected. 它应为 fullmininoneIt should be full, mini, or none. 指定 none 时,测试主机将在超时时终止,但不会收集任何转储。When none is specified, test host is terminated on timeout, but no dump is collected. 意味着 --blame-hangImplies --blame-hang.

  • --blame-hang-timeout <TIMESPAN> (自 .NET 5.0 预览版 SDK 起可用)--blame-hang-timeout <TIMESPAN> (Available since .NET 5.0 preview SDK)

    每测试超时时间,在此时间后,将触发挂起转储并终止测试宿主进程。Per-test timeout, after which a hang dump is triggered and the test host process is terminated. 超时值是采用以下格式之一指定的:The timeout value is specified in one of the following formats:

    • 1.5 h1.5h
    • 90 m90m
    • 5400 s5400s
    • 5400000 ms5400000ms

    如果未使用单位(例如,5400000),则假定该值以毫秒为单位。When no unit is used (for example, 5400000), the value is assumed to be in milliseconds. 与数据驱动的测试一起使用时,超时行为取决于所使用的测试适配器。When used together with data driven tests, the timeout behavior depends on the test adapter used. 对于 xUnit 和 NUnit,会在每个测试用例后更新超时。For xUnit and NUnit the timeout is renewed after every test case. 对于 MSTest,超时用于所有测试用例。For MSTest, the timeout is used for all test cases. 此选项在使用 netcoreapp 2.1 和更高版本的 Windows 上以及在使用 netcoreapp 3.1 和更高版本的 Linux 上受支持。This option is supported on Windows with netcoreapp2.1 and later, and on Linux with netcoreapp3.1 and later. 不支持 macOS。macOS is not supported.

  • -c|--configuration <CONFIGURATION>

    定义生成配置。Defines the build configuration. 默认值为 Debug,但项目配置可以替代此默认 SDK 设置。The default value is Debug, but your project's configuration could override this default SDK setting.

  • --collect <DATA_COLLECTOR_NAME>

    为测试运行启用数据收集器。Enables data collector for the test run. 有关详细信息,请参阅监视和分析测试运行For more information, see Monitor and analyze test run.

    若要在 .NET Core 支持的任何平台上收集代码覆盖率,请安装 Coverlet 并使用 --collect:"XPlat Code Coverage" 选项。To collect code coverage on any platform that is supported by .NET Core, install Coverlet and use the --collect:"XPlat Code Coverage" option.

    在 Windows 上,可以使用 --collect "Code Coverage" 选项收集代码覆盖率。On Windows, you can collect code coverage by using the --collect "Code Coverage" option. 此选项将生成“.coverage”文件,该文件可在 Visual Studio 2019 Enterprise 中打开。This option generates a .coverage file, which can be opened in Visual Studio 2019 Enterprise. 有关详细信息,请参阅使用代码覆盖率自定义代码覆盖率分析For more information, see Use code coverage and Customize code coverage analysis.

  • -d|--diag <LOG_FILE>

    启用测试平台的诊断模式,并将诊断消息写入到指定文件及其旁边的文件。Enables diagnostic mode for the test platform and writes diagnostic messages to the specified file and to files next to it. 正在记录消息的进程可确定创建了哪些文件,如测试主机日志的 *.host_<date>.txt,以及数据收集器日志的 *.datacollector_<date>.txtThe process that is logging the messages determines which files are created, such as *.host_<date>.txt for test host log, and *.datacollector_<date>.txt for data collector log.

  • -f|--framework <FRAMEWORK>

    强制将 dotnet 或 .NET Framework 测试主机用于测试二进制文件。Forces the use of dotnet or .NET Framework test host for the test binaries. 此选项只确定要使用哪种类型的主机。This option only determines which type of host to use. 要使用的实际框架版本由测试项目的 runtimeconfig.json 决定。The actual framework version to be used is determined by the runtimeconfig.json of the test project. 如果未指定,则 TargetFramework 程序集特性用于确定主机的类型。When not specified, the TargetFramework assembly attribute is used to determine the type of host. 如果已从 .dll 中去除此特性,则使用的是 .NET Framework 主机。When that attribute is stripped from the .dll, the .NET Framework host is used.

  • --filter <EXPRESSION>

    使用给定表达式筛选掉当前项目中的测试。Filters out tests in the current project using the given expression. 有关详细信息,请参阅筛选选项详细信息部分。For more information, see the Filter option details section. 若要获取使用选择性单元测试筛选的其他信息和示例,请参阅运行选择性单元测试For more information and examples on how to use selective unit test filtering, see Running selective unit tests.

  • -h|--help

    打印出有关命令的简短帮助。Prints out a short help for the command.

  • --interactive

    允许命令停止并等待用户输入或操作。Allows the command to stop and wait for user input or action. 例如,完成身份验证。For example, to complete authentication. 自 .NET Core 3.0 SDK 起可用。Available since .NET Core 3.0 SDK.

  • -l|--logger <LOGGER>

    指定测试结果记录器。Specifies a logger for test results. 与 MSBuild 不同,dotnet 测试不接受缩写,应使用 -l "console;verbosity=detailed",而不使用 -l "console;v=d"Unlike MSBuild, dotnet test doesn't accept abbreviations: instead of -l "console;v=d" use -l "console;verbosity=detailed".

  • --no-build

    不在运行测试项目之前生成它。Doesn't build the test project before running it. 还将隐式设置 - --no-restore 标记。It also implicitly sets the - --no-restore flag.

  • --nologo

    运行测试,而不显示 Microsoft TestPlatform 横幅。Run tests without displaying the Microsoft TestPlatform banner. 自 .NET Core 3.0 SDK 起可用。Available since .NET Core 3.0 SDK.

  • --no-restore

    运行此命令时不执行隐式还原。Doesn't execute an implicit restore when running the command.

  • -o|--output <OUTPUT_DIRECTORY>

    查找要运行的二进制文件的目录。Directory in which to find the binaries to run. 如果未指定,则默认路径为 ./bin/<configuration>/<framework>/If not specified, the default path is ./bin/<configuration>/<framework>/. 对于具有多个目标框架的项目(通过 TargetFrameworks 属性),在指定此选项时还需要定义 --frameworkFor projects with multiple target frameworks (via the TargetFrameworks property), you also need to define --framework when you specify this option. dotnet test 始终从输出目录运行测试。dotnet test always runs tests from the output directory. 可以使用 AppDomain.BaseDirectory 以使用输出目录中的测试资产。You can use AppDomain.BaseDirectory to consume test assets in the output directory.

  • -r|--results-directory <RESULTS_DIR>

    用于放置测试结果的目录。The directory where the test results are going to be placed. 如果指定的目录不存在,则会创建该目录。If the specified directory doesn't exist, it's created. 默认值为包含项目文件的目录中的 TestResultsThe default is TestResults in the directory that contains the project file.

  • --runtime <RUNTIME_IDENTIFIER>

    要针对其测试的目标运行时。The target runtime to test for.

  • -s|--settings <SETTINGS_FILE>

    .runsettings 文件用于运行测试。The .runsettings file to use for running the tests. TargetPlatform 元素 (x86|x64) 对 dotnet test 不起作用。The TargetPlatform element (x86|x64) has no effect for dotnet test. 若要运行面向 x86 的测试,请安装 .NET Core 的 x86 版本。To run tests that target x86, install the x86 version of .NET Core. 路径上 dotnet.exe 的位数是用于运行测试的内容。The bitness of the dotnet.exe that is on the path is what will be used for running tests. 有关更多信息,请参见以下资源:For more information, see the following resources:

  • -t|--list-tests

    列出已发现的测试,而不是运行测试。List the discovered tests instead of running the tests.

  • -v|--verbosity <LEVEL>

    设置命令的详细级别。Sets the verbosity level of the command. 允许使用的值为 q[uiet]m[inimal]n[ormal]d[etailed]diag[nostic]Allowed values are q[uiet], m[inimal], n[ormal], d[etailed], and diag[nostic]. 默认值为 minimalThe default is minimal. 有关详细信息,请参阅 LoggerVerbosityFor more information, see LoggerVerbosity.

  • RunSettings 参数RunSettings arguments

内联的 RunSettings 作为“-- ”(请注意 -- 后面有空格)后的最后一个命令行参数传递。Inline RunSettings are passed as the last arguments on the command line after "-- " (note the space after --). 内联的 RunSettings 被指定为 [name]=[value] 对。Inline RunSettings are specified as [name]=[value] pairs. 空格用于分隔多个 [name]=[value] 对。A space is used to separate multiple [name]=[value] pairs.

示例:dotnet test -- MSTest.DeploymentEnabled=false MSTest.MapInconclusiveToFailed=TrueExample: dotnet test -- MSTest.DeploymentEnabled=false MSTest.MapInconclusiveToFailed=True

有关详细信息,请参阅通过命令行传递 RunSettings 参数For more information, see Passing RunSettings arguments through command line.

示例Examples

  • 运行当前目录所含项目中的测试:Run the tests in the project in the current directory:

    dotnet test
    
  • 运行 test1 项目中的测试:Run the tests in the test1 project:

    dotnet test ~/projects/test1/test1.csproj
    
  • 在当前目录运行项目中的测试,并以 trx 格式生成测试结果文件:Run the tests in the project in the current directory, and generate a test results file in the trx format:

    dotnet test --logger trx
    
  • 在当前目录运行项目中的测试,并生成代码覆盖率文件(安装 Coverlet 收集器集成后):Run the tests in the project in the current directory, and generate a code coverage file (after installing Coverlet collectors integration):

    dotnet test --collect:"XPlat Code Coverage"
    
  • 在当前目录运行项目中的测试,并生成代码覆盖率文件(仅限 Windows):Run the tests in the project in the current directory, and generate a code coverage file (Windows only):

    dotnet test --collect "Code Coverage"
    
  • 在当前目录中运行项目中的测试,并将详细的测试结果记录到控制台:Run the tests in the project in the current directory, and log with detailed verbosity to the console:

    dotnet test --logger "console;verbosity=detailed"
    
  • 在当前目录下的项目中运行测试,并报告在测试主机发生故障时正在进行的测试:Run the tests in the project in the current directory, and report tests that were in progress when the test host crashed:

    dotnet test --blame
    

筛选选项详细信息Filter option details

--filter <EXPRESSION>

<Expression> 格式为 <property><operator><value>[|&<Expression>]<Expression> has the format <property><operator><value>[|&<Expression>].

<property>Test Case 的特性。<property> is an attribute of the Test Case. 下面介绍了常用单元测试框架支持的属性:The following are the properties supported by popular unit test frameworks:

测试框架Test Framework 支持的属性Supported properties
MSTestMSTest
  • FullyQualifiedNameFullyQualifiedName
  • “属性”Name
  • ClassNameClassName
  • PriorityPriority
  • TestCategoryTestCategory
xUnitxUnit
  • FullyQualifiedNameFullyQualifiedName
  • DisplayNameDisplayName
  • TraitsTraits
NUnitNUnit
  • FullyQualifiedNameFullyQualifiedName
  • “属性”Name
  • TestCategoryTestCategory
  • PriorityPriority

<operator> 说明了属性和值之间的关系:The <operator> describes the relationship between the property and the value:

运算符Operator 函数Function
= 完全匹配Exact match
!= 非完全匹配Not exact match
~ 包含Contains
!~ 不包含Not contains

<value> 是字符串。<value> is a string. 所有查找都不区分大小写。All the lookups are case insensitive.

不含 <operator> 的表达式自动被视为 FullyQualifiedName 属性上的 contains(例如,dotnet test --filter xyzdotnet test --filter FullyQualifiedName~xyz 相同)。An expression without an <operator> is automatically considered as a contains on FullyQualifiedName property (for example, dotnet test --filter xyz is same as dotnet test --filter FullyQualifiedName~xyz).

表达式可与条件运算符结合使用:Expressions can be joined with conditional operators:

运算符Operator 函数Function
| OR      
& ANDAND

使用条件运算符时,可以用括号将表达式括起来(例如,(Name~TestMethod1) | (Name~TestMethod2))。You can enclose expressions in parenthesis when using conditional operators (for example, (Name~TestMethod1) | (Name~TestMethod2)).

若要获取使用选择性单元测试筛选的其他信息和示例,请参阅运行选择性单元测试For more information and examples on how to use selective unit test filtering, see Running selective unit tests.

请参阅See also