如何在VSCode中调试MSTest?

时间:2017-11-02 01:52:42

标签: .net unit-testing visual-studio-code mstest

在VSCode的1.17.2版本中(安装了C#extenion)我已经通过dotnet new mstest将MSTest项目添加到解决方案文件夹中,并使用dotnet add <project_path>添加了对正在测试的程序集的引用。

鉴于下面的两个VSCode任务,我可以成功构建和运行测试;即一切都在建立,单元测试运行并通过。

{
    "version": "2.0.0",
    "tasks": [
        {
            "taskName": "build",
            "command": "dotnet build src/tests/tests.csproj",
            "type": "shell",
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "presentation": {
                "reveal": "silent"
            },
            "problemMatcher": "$msCompile"
        },
        {
            "taskName": "test",
            "command": "dotnet test src/tests/tests.csproj",
            "type": "shell",
            "group": {
                "kind": "test",
                "isDefault": true
            },
            "presentation": {
                "reveal": "silent"
            },
            "problemMatcher": "$msCompile"
        }
    ]
}

然而,我无法使用集成调试器查看断点或以其他方式完成单元测试。我提出的最接近的启动配置将运行测试,但调试器不会遇到断点或附加到任何地方。

    {
        "name": "test",
        "type": "coreclr",
        "request": "launch",
        "preLaunchTask": "build",
        "program": "dotnet",
        "args": ["test"],
        "cwd": "${workspaceRoot}/src/tests",
        "stopAtEntry": true,
        "console": "internalConsole"
    }

我可能遗漏了一些基本的东西但是如何将vscode c#debugger启动或附加到MSTest单元测试?

1 个答案:

答案 0 :(得分:4)

由于缺乏更优雅的解决方案,我最终做到了这一点:

使用以下内容创建set VSTEST_HOST_DEBUG=1 dotnet test Path\\To.Your\\Tests.csproj 文件:

dotnet test

这将启动Starting test execution, please wait... Host debugging is enabled. Please attach debugger to testhost process to continue. Process Id: 13292, Name: dotnet 并等待附加调试器。 运行它也会显示进程ID,这将有助于以后...

{
    "label": "Start MS Test",
    "type": "shell",
    "isBackground": true,
    "command": "${cwd}\\Path\\To.Your\\launchMsTestAndWaitForDebugger.bat",
    "presentation": {
        "echo": true,
        "reveal": "always",
        "focus": false,
        "panel": "shared"
    },
    "problemMatcher": []
}

接下来,我在tasks.json中创建了一个任务来运行这个.bat文件:

    {
        "name": ".NET Core Attach",
        "type": "coreclr",
        "request": "attach",
        "processId": "${command:pickProcess}"
    }

现在我们可以启动dotnet测试并等待调试器,非常好。确保您在launch.json中有一个条目以附加到进程:

ctrl+shift+p

现在Start MS Test并运行.NET Core Attach任务。在输出中查找processid。使用fetch = +refs/pull/*/head:refs/remotes/origin/pr/* 定义启动,选择正确的流程并点击播放。瞧:

enter image description here