Click here to Skip to main content
15,883,749 members
Articles / Programming Languages / C#

Manage TFS Test Cases C# Code

Rate me:
Please Sign up or sign in to vote.
4.85/5 (14 votes)
15 Sep 2015CPOL3 min read 33K   17   2
Manage TFS Test Cases in Microsoft Test Manager C# VB.NET Code

Introduction

To use TFS Test Cases via code, you should first create TFS Collection and Team Test Project. You can find more information in my previous post: “How to: Connect to TFS Team Project C# Code“.

Next you need to connect to a specific test plan. You can read more in the article: “Manage TFS Test Plans C# Code“.

In MS Test Manager, you can edit, create, delete test cases. Here I am going to show you how to do these actions via C# code.

Image 1

Get All TFS Test Cases

Our first job is to create a wrapper class for the TFS Test Case (ITestCase). It will contain only the most important properties of the base core TFS Test Case object and will be serializable because the standard Microsoft objects are not. This means that you cannot use them in web services or put them into the clipboard.

C#
[Serializable]
public class TestCase : BaseNotifyPropertyChanged
{
    [NonSerialized]
    private TeamFoundationIdentityName teamFoundationIdentityName;
    private int id;
    private string title;
    private string area;
    private string createdBy;
    private DateTime dateCreated;
    private DateTime dateModified;
    private Priority priority;
    protected bool isInitialized;

    public string OwnerDisplayName { get; set; }

    public Guid TeamFoundationId { get; set; }

    public int Id
    {
        get
        {
            return this.id;
        }

        set
        {
            this.id = value;
        }
    }

    public string Title
    {
        get
        {
            return this.title;
        }

        set
        {
            if (this.isInitialized)
            {
                UndoRedoManager.Instance().Push(t => this.Title = t, this.title, "Change the test case title");
            }
            this.title = value;
            this.NotifyPropertyChanged();
        }
    }

    public DateTime DateCreated
    {
        get
        {
            return this.dateCreated;
        }

        set
        {
            this.dateCreated = value;
            this.NotifyPropertyChanged();
        }
    }

    public string CreatedBy
    {
        get
        {
            return this.createdBy;
        }

        set
        {
            this.createdBy = value;
            this.NotifyPropertyChanged();
        }
    }

    public DateTime DateModified
    {
        get
        {
            return this.dateModified;
        }

        set
        {
            this.dateModified = value;
            this.NotifyPropertyChanged();
        }
    }

    public string Area
    {
        get
        {
            return this.area;
        }

        set
        {
            if (this.isInitialized)
            {
                UndoRedoManager.Instance().Push(a => this.Area = a, this.area, "Change the test case area");
            }
            this.area = value;
            this.NotifyPropertyChanged();
        }
    }

    public TeamFoundationIdentityName TeamFoundationIdentityName
    {
        get
        {
            return this.teamFoundationIdentityName;
        }

        set
        {
            if (this.isInitialized)
            {
                UndoRedoManager.Instance().Push(t => this.TeamFoundationIdentityName = t, this.teamFoundationIdentityName, "Change the test case owner");
            }
            this.teamFoundationIdentityName = value;
            this.NotifyPropertyChanged();
        }
    }

    public Priority Priority
    {
        get
        {
            return this.priority;
        }

        set
        {
            if (this.isInitialized)
            {
                UndoRedoManager.Instance().Push(p => this.Priority = p, this.priority, "Change the test case priority");
            }
            this.priority = value;
            this.NotifyPropertyChanged();
        }
    }
}

If you want to get all test cases in the current Team Project, you can use the following method.

public static List<TestCase> GetAllTestCasesInTestPlan(ITestManagementTeamProject testManagementTeamProject, ITestPlan testPlan, bool initializeTestCaseStatus = true)
{
    testPlan.Refresh();
    List<TestCase> testCasesList;
    testCasesList = new List<TestCase>();
    string fullQuery =
        String.Format("SELECT [System.Id], [System.Title] FROM WorkItems WHERE [System.WorkItemType] = 'Test Case' AND [Team Project] = '{0}'", testManagementTeamProject.TeamProjectName);
    IEnumerable<ITestCase> allTestCases = testManagementTeamProject.TestCases.Query(fullQuery);
    foreach (var currentTestCase in allTestCases)
    {
        TestCase testCaseToAdd = new TestCase(currentTestCase, currentTestCase.TestSuiteEntry.ParentTestSuite, testPlan, initializeTestCaseStatus);
        if (!testCasesList.Contains(testCaseToAdd))
        {
            testCasesList.Add(testCaseToAdd);
        }
    }

    return testCasesList;
}

If you want to get the test cases from specific test suite, you can use a slightly modified method. The test plan and the current suite are refreshed in order to obtain the latest added test cases. Otherwise, the TFS will return you the cached snapshot of the query.

C#
public static List<TestCase> GetAllTestCaseFromSuite(ITestPlan testPlan, int suiteId, bool includeExecutionStatus = true)
{
    List<TestCase> testCases = new List<TestCase>();
    testPlan.Refresh();
    ITestSuiteBase currentSuite = testPlan.Project.TestSuites.Find(suiteId);
    currentSuite.Refresh();
    foreach (var currentTestCase in currentSuite.TestCases)
    {
        TestCase testCaseToAdd = new TestCase(currentTestCase.TestCase, currentSuite, testPlan, includeExecutionStatus);
        if (!testCases.Contains(testCaseToAdd))
        {
            testCases.Add(testCaseToAdd);
        }
    }
    log.InfoFormat("Load all test cases in the suite with Title= \"{0}\" id = \"{1}\"", currentSuite.Title, currentSuite.Id);
    return testCases;
}

Delete TFS Test Case

Unfortunately, the TFS API doesn’t support delete operations of TFS Test Cases. You can remove them from TFS Test Suites, but they are not actually deleted. You can find them with TFS Queries or using MS Test Manager – Test Case Manager View.

Create TFS Test Case

Here, I will show you how to create a new TFS Test Case without test steps. Only the most basic properties will be initialized. You will be able to find more information about test steps and shared steps in my future TFS API related posts.

C#
public static TestCase Save(this TestCase sourceTestCase, ITestManagementTeamProject testManagementTeamProject, ITestPlan testPlan, bool createNew, int? suiteId)
{
    TestCase currentTestCase = sourceTestCase;
    if (createNew)
    {
        ITestCase testCaseCore = testManagementTeamProject.TestCases.Create();
        currentTestCase = new TestCase(testCaseCore, sourceTestCase.ITestSuiteBase, testPlan);
    }
    currentTestCase.ITestCase.Area = sourceTestCase.Area;
    currentTestCase.ITestCase.Title = sourceTestCase.Title;
    currentTestCase.ITestCase.Priority = (int)sourceTestCase.Priority;
    currentTestCase.ITestCase.Actions.Clear();
    currentTestCase.ITestCase.Owner = testManagementTeamProject.TfsIdentityStore.FindByTeamFoundationId(sourceTestCase.TeamFoundationId);

    if (suiteId != null)
    {
        var newSuite = TestSuiteManager.GetTestSuiteById(testManagementTeamProject, testPlan, (int)suiteId);
        sourceTestCase.ITestSuiteBase = newSuite;
    }
    currentTestCase.ITestCase.Flush();
    currentTestCase.ITestCase.Save();
    if (suiteId != null)
    {
        SetTestCaseSuite(testManagementTeamProject, testPlan, (int)suiteId, currentTestCase);
    }

    currentTestCase.ITestCase.Flush();
    currentTestCase.ITestCase.Save();

    return currentTestCase;
}

The above extension method can be used in two modes – SAVE and UPDATE. If the parameter createdNew is true, a new test case will be created and saved, otherwise the properties of the existing test case will be updated and saved.

If the test case is added to TFS test suite, it should be saved/created in advance because of that we call the Flush-Save methods before the Suite-Test Case association. Also, after the addition to TFS Test Suite, you need to save the test case again.

So Far in the TFS API Series

1. Connect to TFS Team Project C# Code
2. Manage TFS Test Plans C# Code
3. Manage TFS Test Cases C# Code
4. Manage TFS Test Suites C# Code
5. TFS Associate Automated Test with Test Case C# Code
6. Test Cases Statistics with SSRS and TFS Data Warehouse
7. SSRS SQL Server Reporting Services- Subscriptions for Reports

 

If you enjoy my publications, feel free to SUBSCRIBE
Also, hit these share buttons. Thank you!

Source Code

 

The post- Manage TFS Test Cases in MS Test Manager C# VB.NET Code appeared first on Automate The Planet.

All images are purchased from DepositPhotos.com and cannot be downloaded and used for free. License Agreement

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
CEO Automate The Planet
Bulgaria Bulgaria
CTO and Co-founder of Automate The Planet Ltd, inventor of BELLATRIX Test Automation Framework, author of "Design Patterns for High-Quality Automated Tests: High-Quality Test Attributes and Best Practices" in C# and Java. Nowadays, he leads a team of passionate engineers helping companies succeed with their test automation. Additionally, he consults companies and leads automated testing trainings, writes books, and gives conference talks. You can find him on LinkedIn every day.

Comments and Discussions

 
QuestionHow do you add new parameter values inside the test case? Pin
Nitin Bhatnagar10-Sep-19 20:58
Nitin Bhatnagar10-Sep-19 20:58 
QuestionTest cases arn't ment to be deleted Pin
Member 1096422424-Feb-15 4:38
Member 1096422424-Feb-15 4:38 
test cases are ultimately workitems, by tfs's very nature it is supposed to capture/audit everything, not delete it. Even in its source control, a file in source control never gets deleted, current version my say it doesn't but you can always use GetSpecificVersion, even on workitems, rather handy if you make a large screwup edit and saved it, the tfs api lets you get a specific version and override all of its current fields to that

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.