In the previous Getting Started post for this series I covered the basics of creating a connection to the server and getting an instance of ITestManagementTeamProject which is at the core of just about everything you may want to do with the Test Management objects.

This time I’d like to show how to create and modify a Test Plan, add a new Test Suite to it, and then add Test Cases to your new suite.  Then I’ll query it all back and output some basic info about what we’ve created.

I start with the same basic framework I laid out in the Getting Started post, and also reference the post I previously did on Test Points so you may want to review those before proceeding.  Note that in several places I used WIQL for querying test objects from the server, for more on that Duat Le has put together a great post here that goes into depth on that topic.

One last note, beyond the references mentioned in the Getting Started post you need to add a reference to WindowsBase.  Now, on to the code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.TestManagement.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

namespace BlogSamples
{
    class Program
    {
        static void Main(string[] args)
        {
            string serverurl = "http://localhost:8080/tfs";
            string project = "test";
            ITestManagementTeamProject proj = GetProject(serverurl, project);

            // List all Test Plans
            foreach (ITestPlan p in proj.TestPlans.Query("Select * From TestPlan"))
            {
                Console.WriteLine("Plan - {0} : {1}", p.Id, p.Name);
            }

            // Get a Test Plan by its Id
            int myPlansId = 1;
            
            ITestPlan foundPlan = proj.TestPlans.Find(myPlansId);
            Console.WriteLine("Got Plan {0} with Id {1}",
                foundPlan.Name, foundPlan.Id);

            // Let's create a new Test Plan from scratch
            // Only the Name property is required to be set before
            // you can save, but we'll set a few extras here as well.
            ITestPlan plan = proj.TestPlans.Create();
            plan.Name = "My New Test Plan";
            plan.StartDate = DateTime.Now;
            plan.EndDate = DateTime.Now.AddMonths(2);
            plan.Save();

            Console.WriteLine("Created new Plan \"{0}\" with Id: {1}",
                plan.Name, plan.Id);

            // Next let's add a new Test Suite to our plan
            // First, create a static suite (I'll cover Dynamic Suites
            // in a future post)
            IStaticTestSuite newSuite = proj.TestSuites.CreateStatic();
            newSuite.Title = "Acceptance Tests";
            
            plan.RootSuite.Entries.Add(newSuite);
            plan.Save();

            // Let's find the default configuration that was created when
            // we created our Team Project.  We'll need this to add some
            // tests to our new suite (or we could create a new one, but 
            // I'll keep things simple and just get the default one for now)
            ITestConfiguration defaultConfig = null;

            foreach (ITestConfiguration config in proj.TestConfigurations.Query(
                "Select * from TestConfiguration"))
            {
                defaultConfig = config;
                break;
            }

            // I would typically check that defaultConfig is not null here
            // but for brevity sake will skip that.

            // Next we'll create a Testcase to add to our Test Suite
            ITestCase tc = proj.TestCases.Create();
            tc.Title = "Verify X when doing Y";
            tc.Save();

            // Now let's add it to your suite, we still have our reference
            // to the static suite around so we'll use that
            // First we need an "IdAndName" object for our config
            IdAndName defaultConfigIdAndName = new IdAndName(
                defaultConfig.Id, defaultConfig.Name);
            
            // Now we'll set the default configs for our suite
            newSuite.SetDefaultConfigurations(new IdAndName[] {
                defaultConfigIdAndName});

            // Now let's add that testcase
            newSuite.Entries.Add(tc);

            // Now let's save the plan (don't need to explicitly
            // save test suites).
            plan.Save();
            
            // And finally, let's take a look at what we've created.
            Console.WriteLine("Test Plan: {0}", plan.Name);

            foreach (ITestSuiteBase suite in plan.RootSuite.SubSuites)
            {
                Console.WriteLine("\tTest Suite: {0}", suite.Title);

                IStaticTestSuite staticSuite = suite as IStaticTestSuite;

                // Let's Query the Test Points (see my previous post on what
                // Test Points are)
                foreach (ITestPoint point in plan.QueryTestPoints(
                    string.Format("SELECT * FROM TestPoint WHERE SuiteId = {0}",
                    suite.Id)))
                {
                    Console.WriteLine("\t\tTest Point for Testcase \"{0}\" against config \"{1}\"",
                        point.TestCaseWorkItem.Title, point.ConfigurationName);                        
                }
            }
        }


        static ITestManagementTeamProject GetProject(string serverUrl,
            string project)
        {
            TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(TfsTeamProjectCollection.GetFullyQualifiedUriForName(serverUrl));
            ITestManagementService tms = tfs.GetService<ITestManagementService>();

            return tms.GetTeamProject(project);
        }
    }
}