Thursday, June 2, 2011

TFS 2010 SP1 Goody: Using the API to retrieve Code Coverage Information for a Build

There was a new approach for exposing Test related information in TFS 2010 in the API thru the new TestManagementService.  It was particularly easy to get the Unit Test information for a give build URI:

        using (TfsTeamProjectCollection Tfs = new TfsTeamProjectCollection(…)
        {
            Uri myBuild= new Uri(… some build URI…);
            TestManagementService tcm = (TestManagementService) Tfs.GetService<TestManagementService>();

            ITestManagementTeamProject teamProject = tcm.GetTeamProject(… Team Project Name…);

            foreach (var testResult in teamProject .TestRuns.ByBuild(myBuild))
            {
                testResult.Statistics.CompletedTests;
               
            }

        }

With SP1 of Visual Studio and the Team Client, Code Coverage results by build or test run has been exposed as the CoverageAnalysisManager property off ITestManagementTeamProject.

namespace Microsoft.TeamFoundation.TestManagement.Client
{
    public interface ICoverageAnalysisManager
    {
        IBuildCoverage[] QueryBuildCoverage(string buildUri, CoverageQueryFlags flags);
        ITestRunCoverage[] QueryTestRunCoverage(int testRunId, CoverageQueryFlags flags); 
    }
}

So now, if you want extend the example above to iterate thru the Assembly (Module)level Code Coverage information:

foreach (IBuildCoverage coverage in teamProject.CoverageAnalysisManager.QueryBuildCoverage(myBuild.ToString(), CoverageQueryFlags.Modules))
{
    foreach (IModuleCoverage moduleInfo in coverage.Modules)
    {
        moduleInfo.Name;
        moduleInfo.Statistics.BlocksCovered;
        moduleInfo.Statistics.BlocksNotCovered;
        moduleInfo.Statistics.LinesCovered;
        moduleInfo.Statistics.LinesNotCovered;
        moduleInfo.Statistics.LinesPartiallyCovered;
    }
}

No comments:

Post a Comment