如何在Visual Studio代码中运行所有测试

问题描述 投票:34回答:4

最新版本的VS Code已经提供了一种简单的方法来运行单个测试,如Tyler Long's answer指向问题Debugging xunit tests in .NET Core and Visual Studio Code

但是,我正在寻找如何运行VS Code中的测试套件类中包含的所有测试(无需调试)?

我找到的唯一方法是向launch.json添加一个特定的配置,如下所示,但我只能在debug中运行(我想在没有调试的情况下运行它):

{
  "name": ".NET Core Xunit tests",
  "type": "coreclr",
  "request": "launch",
  "preLaunchTask": "build",
  "program": "/usr/local/share/dotnet/dotnet",
  "args": ["test"],
  "cwd": "${workspaceRoot}/test/MyProject.Tests",
  "externalConsole": false,
  "stopAtEntry": false,
  "internalConsoleOptions": "openOnSessionStart"
}
.net visual-studio-code .net-core xunit.net
4个回答
43
投票

有一种更简单的方法来运行所有测试:

  1. 安装.NET Core Test Explorer扩展
  2. 在VS Code中打开.NET Core测试项目,或将dotnet-test-explorer.testProjectPath设置为settings.json中.NET Core测试项目的文件夹路径
  3. 在Explorer视图的.NET Test Explorer中,将自动检测所有测试,并且您可以运行所有测试或某个测试

.NET Test Explorer


14
投票

您可以通过在终端上执行dotnet test来运行项目中的所有测试。如果您已经打开终端,这很方便,但您也可以将它添加到Visual Studio代码中。

如果按Cmd-Shift-P打开命令选项板并键入“test”,则可以运行“运行测试任务”命令。默认情况下,这不会做任何事情,但你可以编辑tasks.json告诉它如何为你运行dotnet test

tasks.json

{
  "version": "0.1.0",
  "command": "dotnet",
  "isShellCommand": true,
  "args": [],
  "tasks": [
    {
      "taskName": "build",
      "args": [ ],
      "isBuildCommand": true,
      "showOutput": "silent",
      "problemMatcher": "$msCompile"
    },
    {
      "taskName": "test",
      "args": [ ],
      "isTestCommand": true,
      "showOutput": "always",
      "problemMatcher": "$msCompile"
    }
  ]
}

这两个任务定义将分别将Visual Studio Code中的Run Build Task和Run Test Task命令链接到dotnet builddotnet test


10
投票

基于GraehamF的答案,tasks.json为dotnet 2.0所需的配置是不同的。

{
"version": "2.0.0",
"tasks": [
    {
        ...
    },
    {
        "label": "test",
        "command": "dotnet",
        "type": "shell",
        "group": "test",
        "args": [
            "test",
            "${workspaceFolder}/testprojectfolder/testprojectname.csproj"
        ],
        "presentation": {
            "reveal": "silent"
        },
        "problemMatcher": "$msCompile"
    }
]

我发现当安装Visual Studio和VS Code时,将csproj引用放在命令属性中(如GraehamF的答案)导致Visual Studio被打开而不是在VS Code中运行测试。

(我会把它放在评论中,但我没有足够的声望点。)


0
投票

类似于@Nate Barbettini的回答,但是对于.Net Core Standard 2.0(netcoreapp2.0)。

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "test",
            "command": "dotnet test path/to/test-project.csproj",
            "type": "shell",
            "group": "test",
            "presentation": {
                "reveal": "silent"
            },
            "problemMatcher": "$msCompile"
        }
    ]
}
© www.soinside.com 2019 - 2024. All rights reserved.