Thursday, 28 January 2016

Attach process at runtime for debugging in Visual Studio

With Integration tests a common scenario comes into picture. Integration tests always depend on system components e.g. Database, Services etc. If the Integration test is failing un-expectedly then it might require to debug the test including that component which are usually part of the same VS solution. Recently I came across this SO question Question seemed legit because while debugging a test, attaching a process again and again to debug becomes really annoying.
To make dependent components like services, I usually invoke the process to launch e.g. ConsoleApplication project in same solution. Its like simply Add a helper class to invoke the process.

Now in the TestInitialize and TestCleanup methods (I’m using NUnit in this sample code so it would be TestFixtureSetup and TextFixtureTearDown methods) I would start the process and kill the respective process. Here the Integration test is a sample from one of my Github project WCFDynamicProxy. In this Test I’ll be invoking a Dummy service instance hosted in a Console application. Then completion of test just kill the process.

Now, Comes the part to attach this process for debugging. This is pretty tricky one. I found an VS Addin from Visual studio team to attach child process automatically to current debugger but it seems it only works with "F5" debugging.

Then I found this SO post and It really worked amazingly. I have done a little customization to get the process Id as argument:

Note: You need to add the the VS automation library EnvDTE from AddReference -> Extentions. Also the VS version might be different. I was using Visual Studio 2013 so it’s ‘VisualStudio.DTE.12.0’. Change it as per your need.

Now in the ProcessInvoker class Add the call to AttachDebugger utility class after the process launch statement.

When I launched a test for debugging it worked like charm. The process was invoked, attached to VS and was able to debug other process code. You can verfiy it from menu –> Debug –> Attach to process –> Locate the process expected to be attached.

Checkout the working code here. specially WcfDynamicProxy.Tests in the solution. If you like this post please share, like to support this blog.

No comments:

Post a Comment