To associate TFS Test Cases to automated tests 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 particular test plan. You can read more in the article: Manage TFS Test Plans in MS Test Manager C# Code. Crud operations with TFS Test Cases are discussed in my other post: Manage TFS Test Cases in MS Test Manager C# Code.
How to Get Association Information from TFS Test Case Object?
First you need to create an appropriate wrapper class for the automation properties- TestName, Assembly and Type.
In order to create the object from an already associated TFS Test Case, use the following extension method to the core TFS Test Case entity ITestCase.
The ITestCase association property Implementation is just a string like the following:
The string uses the following format- MethodId,TestName,Assembly,Type.
TFS Associate Automated Test with Test Case C# Code
Before the actual association, you will need one more class. An abstraction around the properties of the automated test like full name, class name and method id.
The actual association code is pretty simple. We use again an extension method to ITestCase.
We use the properties previously initialized in our Test object to create the internal TFS entity ITmiTestImplementation that holds the association information. Then we assigned it to our TFS Test Case. The data will be persisted when the test case object is saved. To prevent exceptions, you need to pass a valid information. The first three parameters- fullName, className, testType are easy to get. The method id is the hardest to obtain. Bellow, I am going to show you how to generate it.
Using reflection you can get the metadata of your test method that is present in the reflection type MethodInfo. The method ID is as you can see a GUID created from the special hash value of the full name of the method.