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:

testcasestep1

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)); // https://mytfs.visualstudio.com/DefaultCollection
    tfs.Authenticate();
 
    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";
        testCase.Actions.Add(newStep); 
    }
 
    testCase.Save();
 
 
}

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:

testcasestep2

References

https://msdn.microsoft.com/en-us/library/microsoft.teamfoundation.testmanagement.client.itestmanagementteamproject.aspx?f=255&MSPPError=-2147217396

http://blogs.microsoft.co.il/shair/2013/10/07/tfs-api-part-51-adding-test-step-amp-shared-step/

https://blogs.msdn.microsoft.com/visualstudioalm/2011/12/30/how-to-get-the-test-case-associated-with-the-unit-test/



Profile picture

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

© Paul Michaels 2024