Search code examples
unit-testingmstesttfs-sdk

Querying failed unit tests from TFS-SDK?


Given a TFS build detail (IBuildDetail) with .Status of PartialSuccess, and .TestStatus of Failed how might I go about retrieving the list of tests (MSTest) that have failed on that build?

I have a working sandbox in which I can contact TFS via the SDK and retrieve the latest PartialSuccess build, but can't seem to find which service might have this unit test data and how I might go about querying it.

Can anyone shed some light?


Solution

  • This article is a great resource, actually it was the only one I had found available when I was searching something similar.
    In general you need access to ITestManagementService.
    Given you already have connection to a teamProjectCollection and a buildDetail, something like this should work out for you :

    var tstService = (ITestManagementService)teamProjectCollection.GetService(typeof(ITestManagementService));
    ITestManagementTeamProject testManagementTeamProject = tstService.GetTeamProject(buildDetail.TeamProject);
    
    IEnumerable<ITestRun> testRuns =  testManagementTeamProject.TestRuns.ByBuild(buildDetail.Uri);
    
    foreach (var testRun in testRuns)
    {
        ITestCaseResultCollection testcases = testRun.QueryResultsByOutcome(TestOutcome.Failed);
        foreach (var testcase in testcases)
        {
            Console.WriteLine("TestCase ID: " + testcase.TestCaseId);
            Console.WriteLine("TestCase Title: " + testcase.TestCaseTitle);
            Console.WriteLine("Error Message: " + testcase.ErrorMessage);                  
        }
    }
    

    (This code is basically a copy from the article above, it is work by Anuj Chaudhary)

    Remember to add "Microsoft.TeamFoundation.TestManagement.Client" in your ref list.