Friday, March 28, 2014

How to subsribe for Unit test run events in extension for Visual Studio?

I've had an idea to write extension for Visual Studio to play sounds on certain events.
In the first iteration I needed next events: build complete, breakpoint hit, unit test run finished.

Why? Because when you work with big solutions and big number of tests sometimes it takes a lot of time to wait for end of compilation/tests or when breakpoint is hit, especially if it is conditional. Usually I switch to different activities and miss moment when those actions end.

While build and debug events are pretty trivial (with one small know-how: in order to listen to the DebuggerEvents events you need to maintain a reference to DebuggerEvents itself. ), with test events things are bit more complicated. The DTE object do not provide unit test events. But solution was found and here how it can be done:

 
protected override void Initialize()
        {
            base.Initialize();


            var applicationObject = (DTE2)GetService(typeof(DTE));

            var componentModel =
                Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(SComponentModel)) as IComponentModel;


            var operationState = componentModel.GetService< IOperationState>();
            operationState.StateChanged += OperationStateOnStateChanged;
        }

        private void OperationStateOnStateChanged(object sender, OperationStateChangedEventArgs operationStateChangedEventArgs)
        {
            if (operationStateChangedEventArgs.State.HasFlag(TestOperationStates.TestExecutionFinished))
            {//Do stuff}
        }

Next assembly needs to be referenced:

   $(DevEnvDir)\CommonExtensions\Microsoft\TestWindow\Microsoft.VisualStudio.TestWindow.Interfaces.dll

If you want to use it in extension for Visual Studio 2012, one more reference is needed:

      $(DevEnvDir)\PublicAssemblies\Microsoft.VisualStudio.ComponentModelHost.dll

By the way, I published those extension, it can be found here: Visual Studio Ding extension

No comments:

Post a Comment