Execute Custom Scripts Before/After the Test Run

PROBLEM

  • I would like to invoke a custom script once the test finishes. The custom script must have access to newly-generated test results.
  • I would like to invoke a custom script just before the test starts executing.

SOLUTION

Override the OnAfterTestCompleted(TestResult result) method for the "after" script and the OnBeforeTestStarted() method for the "before" script. They are both members of the BaseTest class that are invoked once the test finishes or before it starts. 

 

First, create a coded step in order to generate a code-behind file. Then open the code-behind class and add the override definition inside the BaseTest class.

Standalone version

  1. If your test doesn't contain any coded steps, add a Script Step in order to generate the code-behind file.
  2. Once you add the script step, click View Class to make the BaseTest class visible.
  3.  

     

  4. Add the override definition inside the BaseTest, but not inside another method/coded step. 
  5.  

Visual Studio plugin

  1. If your test doesn't contain any coded steps, click the Add Code-Behind File button. See here for more information.
  2. If you test contains a coded step, right click it and select View Code to go to the code-behind file.
  3.  

     

  4. Write the override definition inside the BaseTest (but not inside another method/coded step).

The Override Definition

The TestResult object lets you access the test results from the run that just finished (i.e. the one invoking the OnAfterTestCompleted method):

 

public override void OnAfterTestCompleted(TestResult result)
{
    string overall = Convert.ToString(result.Result);
    Log.WriteLine(overall);
    result.ExportToResultFile(@"C:\", result.TestName);
}

 

The OnBeforeTestStarted method allows you to perform actions required for the initialization of your test (starting scripts, etc.):

 

public override void OnBeforeTestStarted()
{
    this.ExecuteTest("Folder1\\WebTest2.tstest");
}

 

You can use logic from assemblies in these methods. First add references to the assemblies. For Test Studio Standalone version, see the article on how to Add an Assembly Reference.