At our recent TechEd event, one of the most common questions that we are asked it if it is possible to profile a unit test. This is due to developers seeing a unit test running slowly and they want to pop over quickly to the profiler to investigate the cause of the slowdown. But don’t you worry; we’ve got you covered with seamless integration.
Pictured below is my IDE containing a simple project containing an empty foo function. I have created a unit test for this function, which you can see on the right side of the screen in the Test View window. I have run the test, so we can see the “Passed” result of the run at the bottom of the screen in the Test Results window.
Say that footest in running slower then we would like, and we want to profile its performance. The first step is to right click on the results of the test run in the Test Results window, and select “Create Performance Session” from the context menu.
This brings up the performance wizard, where you can specify settings for your new performance session. For profiling unit tests, you will almost always want to leave the profiler in instrumentation mode (the default setting) so that you just get data relevant to the function you are unit testing. By selecting all the default options in the wizard, I’m able to create the new performance session pictured below. As you can see, the unit test is selected as a launch item and the assembly that we are unit testing is selected to be instrumented to collect profiling data. This means that launching the performance session will launch the unit test, but will only collect profiling data from the function which you are unit testing (Note: if you want to profile your actual test, instead of the function being unit tested, just selected the unit test for instrumentation from its right-click menu and unselect the target assembly from being instrumented).
To launch the unit test for profiling, just click the launch button (the one with the green arrow right next to the combo box that says “Instrumentation”) in the Performance Explorer. The test will run as normal, creating a new result in the Test Results window. And you will get a new performance report detailing the performance of the function being unit tested.