Programmatically Create Test Case Steps

December 07, 2016

In this earlier post, I discussed how to create a test case via the TFS API. For my next trick, I’m going to create some test case steps.

The first thing you need is the TestManagement Client:


Once this is installed, the rest is quite straightforward; here’s the method to create the steps:

private static void AddTestCaseSteps(string uri, Project project, int testCaseId, string[] steps)
    TfsTeamProjectCollection tfs;
    tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(uri)); //
    ITestManagementService service = (ITestManagementService)tfs.GetService(typeof(ITestManagementService));
    ITestManagementTeamProject testProject = service.GetTeamProject(project);
    ITestCase testCase = testProject.TestCases.Find(testCaseId);
    foreach (string step in steps)
        ITestStep newStep = testCase.CreateTestStep();
        newStep.Title = step;
        // newStep.ExpectedResult = "Expected result";

As you can see, the ITestManagementService does a lot of the work for you, and once you have the test case, the rest is straightforward. Here’s what the CreateNewTestCase looks like now:

private static ActionResult CreateNewTestCase(string uri, Project project, WorkItem testedWorkItem, string description, string assignee, string[] reproductionSteps)
    WorkItemType workItemType = project.WorkItemTypes["Test Case"];
    // Create the work item. 
    WorkItem newTestCase = new WorkItem(workItemType);
    newTestCase.Title = $"Test {testedWorkItem.Title}";
    newTestCase.Description = description;
    newTestCase.AreaPath = testedWorkItem.AreaPath;
    newTestCase.IterationPath = testedWorkItem.IterationPath;
    newTestCase.Fields["Assigned To"].Value = assignee;
    // Copy tags
    newTestCase.Fields["Tags"].Value = testedWorkItem.Fields["Tags"].Value;
    ActionResult result = CheckValidationResult(newTestCase);
    if (result.Success)
        CreateTestedByLink(uri, testedWorkItem, result.Id);
        AddTestCaseSteps(uri, project, result.Id, reproductionSteps);
    return result;

Finally, here’s the test case:



Profile picture

A blog about one man's journey through code… and some pictures of the Peak District

© Paul Michaels 2024