Skip to content

HOW TO Debug a test

Scott Hutchinson edited this page Apr 19, 2020 · 5 revisions

One way is to attach the debugger to a running dotnet test.

Call the following function at the beginning of the test you want to debug to wait on the debugger:

let debugBreak () = 
    if not System.Diagnostics.Debugger.IsAttached then
      printfn "Please attach a debugger, PID: %d" (System.Diagnostics.Process.GetCurrentProcess().Id)
    while not System.Diagnostics.Debugger.IsAttached do
      System.Threading.Thread.Sleep(100)
    System.Diagnostics.Debugger.Break()

Before you run the tests, you must configure vstest to output the process ID to the terminal. You do that by setting the environment variable VSTEST_HOST_DEBUG to 1 for the process scope. How you do that depends on your operating system. In Windows, run VSTEST_HOST_DEBUG=1 in a git bash terminal, or run $env:VSTEST_HOST_DEBUG=1 in a PowerShell terminal. When you're done debugging, either set it back to 0, or kill the terminal and use a new one for testing without debugging.

Run the tests, usually with dotnet test, which will wait until the debugger is attached. You should see a process ID in the terminal output.

Now in VSCode in the Debug pane on the left, select the configuration .NET Core Attach, and click the Start Debugging button.

(If you don't already have the configuration .NET Core Attach, then add it. Let IntelliSense help you add it to the launch.json file. It should look like this:

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

)

Select the test process with the process ID from the terminal window, and the debugger should attach and break at some external line of code. Click the continue button and then it should break where you put the Debugger.Break call.

NOTE: You can filter the test to run with dotnet test --filter "TestName"

NOTE: See the complete list of tests with dotnet test --list-tests

Clone this wiki locally