How To: Get the Test Case associated with the unit test?

For running and managing unit tests using Microsoft Test Manager (MTM), the users have to do tcm testcase /import of the test assembly.  This step creates a test case work item corresponding to unit test on the client side.  With this, users can do many new scenarios – most importantly start viewing the history/trend of the result.

A FAQ that I have heard many times in internal and external forums is around this is -

Q: How to determine programmatically retrieve the test case artifact corresponding to this unit test?

A: Because of various reasons (legacy, loose coupling, extensibility etc), the unit test does not have any direct reference to the test case artifact.  However, one can get the corresponding test case artifact easily with few lines of code -

 
        private ITestCase GetTestCase()
        {
            // Get the TFS server and project. If those are constant, then hard-code,
            // else get it from Environment Variables or config file etc.
            string serverName = "https://gautamg-tcm1:8080/tfs/defaultcollection";
            string projectName = "GautamG.unit.1";

            // Get Test Management project.
            TfsTeamProjectCollection tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(serverName));
            ITestManagementService testService = tfs.GetService<ITestManagementService>();
            ITestManagementTeamProject project = testService.GetTeamProject(projectName);

            // Query the test case.
            string interestedFields = "[System.Id], [System.Title]"; // and more
            string testCaseName = TestContext.FullyQualifiedTestClassName + "." + TestContext.TestName;
            string storageName = Path.GetFileName(Assembly.GetExecutingAssembly().CodeBase);
            string query = string.Format(CultureInfo.InvariantCulture,
                "SELECT {0} FROM WorkItems WHERE Microsoft.VSTS.TCM.AutomatedTestName = '{1}'" +
                "AND Microsoft.VSTS.TCM.AutomatedTestStorage = '{2}'",
                interestedFields, testCaseName, storageName);

            ITestCase foundTestCase = null;
            IEnumerable<ITestCase> testCases = project.TestCases.Query(query);
            if (testCases.Count() == 1)
            {
                foundTestCase = testCases.First();
            }

            return foundTestCase;
        }

To compile the above code, you will need reference to following dll (and include namespaces appropriately) -

image

- Gautam