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

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

  • Comments 1

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 = "http://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

Leave a Comment
  • Please add 4 and 8 and type the answer here:
  • Post
  • In my current project I need to pass the value from TFS Test Case custom field to Unit Test. I want to have one Unit Test which will be assign as automated test to all TFS Test Cases and during execution process I want to execute test specific logic based on this custom field value. In my case your solution will not work properly as it will find all my TFS Test Cases. Could you suggest me any other approach how I could find the TFS Test Case which execute my Unit Test?  

Page 1 of 1 (1 items)