Service Test 11: Programmatically Set and Get Test Variable Values
Posted on Jul, 2012 by Admin
Test Variables in Service Test 11 are global variables that can be accessed later in the test script, either by linking to the variable in the GUI (Link to a Data Source) or by setting the variable in the GUI (Set Test Variable activity). Both can also be done programmatically using C#. For example, it may be necessary to set a Test Variable inside an activity Event (instead of using the Set Test Variable activity). In this post, we cover the methods available within Service Test to set and retrieve Test Variables.
Create a Test Variable
Before we can programmatically manipulate test variables, we must first declare (add) a Test Variable.
- Click an empty area in the Test Flow.
- In the Test Property Sheet, click the Test Variables button.
- Click the + button.
- Give the User Variable a name. In this example, we are going to use Flight_Number.
That’s all there is to it! Now we can use the Test Variable named Flight_Number anywhere in this Service Test script.
Set a Test Variable Value
The C# code below will set a Test Variable declared within the test Context. This code can be used within an activity Event or within a Custom Code activity:
this.Context.TestProfile.SetVariableValue("Flight_Number","<value>");
Or, access the Test Profile variable value by accessing the Context of the activity name (e.g., CodeActivity8):
this.CodeActivity8.Context.TestProfile.SetVariableValue("Flight_Number","<value>");
Get a Test Variable Value
The C# code below will retrieve a Test Variable declared within the test Context. Just like setting a Test Variable, the code below can be used within an activity Event or within a Custom Code activity:
this.Context.TestProfile.GetVariableValue("Flight_Number");
Or, access the Test Profile variable value by accessing the Context of an activity name (e.g., CodeActivity8):
this.CodeActivity8.Context.TestProfile.GetVariableValue("Flight_Number");
Conclusion
Remember that you should only programmatically set or retrieve Test Variables when it is not possible to accomplish the same task within the Service Test GUI. Use the Set Test Variable activity (Miscellaneous) or Link to a Data Source (Test Variable) when possible. Keep it simple.
Don’t hesitate to ask questions or let us know if you have any issues by posting a comment below!