This article provides insights into the dotnet test
CLI command, including its history compatibility with both VSTest and Microsoft.Testing.Platform (MTP).
Команда dotnet test
работает в двух основных режимах:
- Режим VSTest: это режим по умолчанию
dotnet test
и единственный режим, доступный до пакета SDK для .NET 10. Он предназначен в основном для VSTest, но также может запускать тест Microsoft.Testing.Platform с помощью пакета NuGet Microsoft.Testing.Platform.MSBuild.
- Режим Microsoft.Testing.Platform: представлен с пакетом SDK для .NET 10, этот режим поддерживает исключительно тестовые приложения, созданные с помощью Microsoft.Testing.Platform.
VSTest mode of dotnet test
В течение длительного времени VSTest была единственной тестовой платформой в .NET. Следовательно, dotnet test
был разработан исключительно для VSTest, с всеми параметрами командной строки, адаптированными к VSTest.
The process involves invoking the VSTest
MSBuild target, which triggers other internal targets to run and ultimately runs vstest.console. Все dotnet test
параметры командной строки переводятся в эквиваленты в vstest.console.
Запуск проектов MTP с помощью режима VSTest
dotnet test
was designed to run VSTest projects in VSTest mode. However, you can run MTP projects in dotnet test
VSTest mode by using the Microsoft.Testing.Platform.MSBuild package. From the user's perspective, this support is enabled by setting the TestingPlatformDotnetTestSupport
MSBuild property to true
(it's false
by default for backward-compatibility reasons). When this property is set to true
, Microsoft.Testing.Platform.MSBuild changes the VSTest
target behavior, redirecting it to call InvokeTestingPlatform
.
InvokeTestingPlatform
is an MSBuild target included in Microsoft.Testing.Platform.MSBuild that's responsible for correctly running MTP test applications as executables. VSTest-specific command-line options, such as --logger
, are silently ignored in this mode. To include MTP-specific arguments, such as --report-trx
, you must append them after an additional --
. Например: dotnet test -- --report-trx
.
Примечание
MSTest and NUnit use the Microsoft.Testing.Extensions.VSTestBridge package. By setting EnableMSTestRunner
or EnableNUnitRunner
(which enables Microsoft.Testing.Platform), your test project will support both VSTest and Microsoft.Testing.Platform.
In that scenario, if you use the VSTest mode of dotnet test
and do not set TestingPlatformDotnetTestSupport
to true, you are essentially running entirely with VSTest, as if EnableMSTestRunner
and EnableNUnitRunner
are not set to true.
Примечание
It is highly recommended to set the TestingPlatformDotnetTestSupport
property in Directory.Build.props
. This ensures that you don't need to add it to every test project file individually. Additionally, it prevents the risk of introducing a new test project that doesn't set this property, which could result in a solution where some projects use VSTest while others use Microsoft.Testing.Platform. This mixed configuration might not work correctly and is an unsupported scenario.
The following list outlines the command-line options of dotnet test
command in VSTest mode that are supported by Microsoft.Testing.Platform. These options are specific to the build process and not passed down to VSTest, which is why they work with MTP.
-a|--arch <ARCHITECTURE>
--artifacts-path <ARTIFACTS_DIR>
-c|--configuration <CONFIGURATION>
-f|--framework <FRAMEWORK>
-e|--environment <NAME="VALUE">
--interactive
--no-build
--nologo
--no-restore
-o|--output <OUTPUT_DIRECTORY>
--os <OS>
-r|--runtime <RUNTIME_IDENTIFIER>
-v|--verbosity <LEVEL>
Совет
Аргументы командной строки тестового приложения можно настроить с помощью TestingPlatformCommandLineArguments
свойства MSBuild:
<PropertyGroup>
...
<TestingPlatformCommandLineArguments>--minimum-expected-tests 10</TestingPlatformCommandLineArguments>
</PropertyGroup>
Дополнительные сведения о выполнении проектов MTP в режиме dotnet test
VSTest см. в разделе "Использование Microsoft.Testing.Platform с режимом dotnet test
VSTest".
Дополнительные технические сведения
В dotnet test
режиме VSTest используется --
для указания аргументов RunSettings. Изначально dotnet test
предназначалось для передачи этих аргументов в качестве свойства MSBuild, которое называется VSTestCLIRunSettings
. Таким образом, при выполнении тестовых приложений MTP в VSTest режиме мы переопределяем значение VSTestCLIRunSettings
для представления аргументов приложения.
При запуске dotnet test
в режиме VSTest рекомендуется избегать одновременного включения VSTest и Microsoft.Testing.Platform в одном решении.
Этот сценарий официально не поддерживается, и следует учитывать следующее:
- Параметры командной строки, относящиеся к VSTest, будут применяться только к проектам VSTest, а не к тестовых приложениям MTP.
- Параметры командной строки, относящиеся к MTP, указанные после #D0, будут рассматриваться как аргументы RunSettings для проектов VSTest.
- To run MTP test applications in
dotnet test
VSTest mode, you should use Microsoft.Testing.Platform.MSBuild
, pass MTP-specific command-line options after the extra --
, and set TestingPlatformDotnetTestSupport
to true
.
- Параметры командной строки, ориентированные на VSTest, игнорируются автоматически.
Из-за этих проблем .NET ввел новый dotnet test
режим, специально разработанный для MTP. Мы рекомендуем пользователям MTP перейти с режима VSTest dotnet test
на новый режим, используя SDK для .NET 10.
Чтобы устранить проблемы, возникающие при запуске dotnet test
с помощью MTP в режиме VSTest, .NET представила новый режим в пакете SDK для .NET 10, который специально предназначен для MTP.
Чтобы включить этот режим, добавьте dotnet.config
файл в корневой каталог репозитория или решения.
[dotnet.test:runner]
name = "Microsoft.Testing.Platform"
Примечание
Формат изменится с dotnet.test:runner
на dotnet.test.runner
в пакете SDK для .NET 10, предварительная версия 4.
Так как этот режим специально предназначен для Microsoft.Testing.Platform, ни TestingPlatformDotnetTestSupport
, ни дополнительный --
не требуются.
Важно!
Этот режим совместим только с Microsoft.Testing.Platform версии 1.7.0 и более поздними версиями.
Важно!
Если тестовый проект поддерживает VSTest, но не поддерживает MTP, будет создана ошибка.
Совет
Аргументы командной строки тестового приложения можно настроить с помощью TestingPlatformCommandLineArguments
свойства MSBuild:
<PropertyGroup>
...
<TestingPlatformCommandLineArguments>--minimum-expected-tests 10</TestingPlatformCommandLineArguments>
</PropertyGroup>