Search code examples
visual-studio-2022

Automatically start debugging sub-process only when started from VS-TestExplorer


I have written a testadapter that mainly starts another process and delegates executing my unit-tests in that process. So in fact my adapter is just the bridge between vstest-host and my other process. Let's call that process MyProcess.exe.

Now I want to start debugging my tests in that process. However when using VS-text-explorer, the debugger immediately attaches to the vstest-host-process (testhost.net472.x86.exe in my case). What I want instead is to attch the debugger when MyProcess.exe spins up. So effetivly I want to skip jumping into the host-process when debugging, but instead directly debug MyProcess.exe.

So this is my workflow:

VS Test Explorer --> Debug unit-test
  --> new testhost-process
  --> debugger is attached to testhost-process
  --> start MyProcess.exe within my adapter
      --> debug MyProcess.exe instead of testhost

Of course I can manually attach to the process. But then the debugger is either attached to two processes, or I need a second instance of VS running, which I both find odd. I also tried to add a Debugger.Launch in my own process. However that assumes a further user-interaction, while I actually already indicated that I want to debug my tests. So this is kind of doubled. Also this doesn't allow me, to not attach a debugger when only running the tests or when just running MyProcess.exe outside of VS.


Solution

  • Inspired by the code from here https://github.com/microsoft/vstest/tree/main/src/AttachVS I was able to attach the already running VS to my own process. So in my adapter I am calling the following code:

    public void RunTests(IEnumerable<TestFixtureWrapper> fixtures, IRunContext runContext, IFrameworkHandle frameworkHandle)
    {
        var process = // get the process you want to debug
        if(runContext.IsBeingDebugged)
        {
             DebuggerUtility.AttachVSToProcess(process.Id, Process.GetCurrentProcess().Id);
        }
        // ... do something
    }
    

    This will attach the debugger only when you're already within a debug-session when the adapters Run-method is called by vstest. The only drawback is, that you're still attached to two processes. But at least you don't need to manually attach.