Blog to understand automation concepts in QTP, Selenium Webdriver and Manual Testing concepts

Different Ways to exit from a QTP test: Using ExitTest, AOM and LoadandRunAction

In QTP, Framework should ensure that test is exited as soon test is failed, since there is no point in going forward with execution.
To ensure proper exit from QTP test, we can either use error handling using recovery scenario or vb script. In case of error handling using vbscript, we can exit a test at runtime in following ways.


Using ExitTest Statement

ExitTest statement exits a test once executed in script.But in scripts with functions called from other functions in different libraries and in case if there is multiple nesting of functions within different libraries, ExitTest statement on execution does not stop the test execution.
To understand this, suppose there is Test A and there are 4 different libraries(vbs files) f1,f2,f,3,f4  in which functions are stored and the action in Test A calls function from library f1 which further calls function from library f2 ans so on. In such cases, sometimes exitTest does not get executed and moves to next test without exiting the test.
To exit from test in scenario where ExitTest is not working properly, we can exit from test in below ways:


 Using QTP AOM

 Use following code to exit test in case exitstatement is not working.
Dim qtAppObj
Set qtAppObj = CreateObject("quicktest.application")
qtAppObj.Test.Stop

Using LoadandRunAction

Create a test with Action  Action1. In Action , only write ExitTest. Save the test.
Now in the test, where exitTest is not working properly, instead of ExitTest, write below code:

LoadandRunAction "c:\Test1","Action1"

Once this line of code is executed, QTP will exit the test.

Please go through the below posts for understanding of :

How to execute multiple external tests action using LoadandrunAction from QTP test

In QTP, we can execute external tests actions from a QTP test using LoadandRunAction Method. This method was introduced Post QTP 10, and is very useful to execute multiple tests from a test.Using This method we can execute reusable actions.


Syntax for LoadandrunAction is:



LoadAndRunAction "C:\Documents\qtp\test", "Action1", oneIteration


This will load Action1 from test in the script in which it is called.

Benefits of LoadandRunAction  are as follows:


  • Loads Action from external test dynamically at run time.

  • Can be useful to execute multiple tests in batch from the driver script which will call multiple tests action using LoadandrunAction

  • To run a test from QC, Test Path starts with [QualityCenter] Subject followed by folder structure in QC e.g "[QualityCenter] Subject\TestAutomation/Module1/Test1"



How to share values between various actions in a test in QTP


Below are the various ways by which values can be transferred between various actions in a test.

Sharing Values via the Global Data Table

Value generated in one action can be shared  with other actions in your test by storing the value in the global Data Table. Each Action in the test can access the global data table and hence can access data from the global data table. For details on how to access various in a data table, see Working With data Tables in QTP


Sharing Values Using Environment Variables

Environment variables are also shared between actions and can be used to share information between various action in the test. Also values can be parameterized using environment variable. To create an environment variable, loading environment variable, and details on environment variable, Please see post on Environment Variables in QTP

Sharing Values Using the Dictionary Object

Values between various actions in a test can be done creating a global dictionary object, and using properties of dictionary object.Below are the steps to share values between actions using globaldictionary object:

To use the Dictionary object, you must first add a reserved object to the registry (in HKEY_CURRENT_USER\Software\Mercury Interactive\QuickTest Professional\MicTest\ReservedObjects\) with ProgID = "Scripting.Dictionary". For example: HKEY_CURRENT_USER\Software\Mercury Interactive\QuickTest Professional\MicTest\ReservedObjects\GlobalDictionary


Once object has been added, we can add and remove values to the Dictionary in one action and retrieve the values in another action from the same test using scripting dictionary methods.For details on Scripting Dictionary, Please see Working with dictionary Object


 

Code to send mail with multiple attachments using Outlook.Application Object in QTP

The below function will send mail to recipient  and add multiple attachments in the mail through Outlook Object.



call func_SendMailUsingOutlook("aa@abc.com", "test", "body", "c:\bdlog.txt>c:\testlog.txt")


Function func_SendMailUsingOutlook(strRecipient, strSubject, strBody, AddMultipleAttachment)


   '''Create an instance of Outlook application    Set objol=CreateObject("Outlook.Application")

    Set objMail=objol.CreateItem(0)

    objMail.to=strRecipient

    objMail.Subject=strSubject

    objMail.Body=strBody

  ''Add multiple attachments to mail

strAttachments = split(AddMultipleAttachment,">")

intCount = ubound(strAttachments)

For i = 0 to (intCount)

    If (strAttachments(i) <> "") Then

        objMail.Attachments.Add(strAttachments(i))

    End If

Next

    objMail.Send

    objol.Quit

    Set objMail = Nothing

    Set objol = Nothing

End Function


How to debug a test in QTP: Complete Tutorial

Debugging is the process of locating and fixing or bypassing bugs in computer program code.Before starting debugging in QTP,We need to install Microsoft debugger for debugging. This can be done during QTP Installation.

Below are the options available in Debug Menu and will discuss the same in detail:



Pause:

To detect and isolate defects in a test or function library, you can control the run session using the Pause command. This will pause the test run and you can check for state of objects, and values in variable at the moment of pause to get the issue. You can temporarily suspend a run session by choosing Debug > Pause or clicking the Pause button. The Test execution will resume if we Press F5 or Run.

Step Into :

While navigation into a function definition from the function called in script. We can use Debug>Step Into or Press F11 or click on Step into button. Using Step Into, we can debug in the function called in script and run each step line by line in the function.

Step Over:

Step Over does debugging line by line in the script, but does not debug into a function called within script, but executes the function as a step and moves to next step in the Test. We can use Step Over using F10 Key or Debug>Step Over or icon for Step Over in the QTP IDE.

Step Out:

Suppose we have step into a function as explained in Step To, and wants to come out of the function or Action, we use Step Out Option. We can use Step Over using shift + F11 Key or Debug>Step Out or icon for Step Out in the QTP IDE.

Run To Step:

You can instruct QTP to run from the beginning of the test or action or from the current location in the test and to stop at a particular step. This is similar to adding a temporary breakpoint to a step.
To select Run to Step, Insert your cursor in the step in which you want QuickTest to stop the run and choose Debug > Run to Step or press Ctrl+F10

Debug from Step

You can instruct QuickTest to begin your debug session from a particular step instead of beginning the run at the start of the test or action. Before you start debugging from a specific step, make sure that the application is open to the location.
To debug a test from step, Insert your cursor in the step where you want QuickTest to start the run and choose Debug > Debug from Step.

Using BreakPoints in QTP:

We can use breakpoints to suspend a run session and inspect the state of your application or mark a point from which to begin stepping through a test or function library.
Breakpoints are applicable only to the current QuickTest session and are not saved with the tests.
Test execution pauses at the step where we provide breakpoint. A breakpoint can be inserted using Debug > Insert/Remove Breakpoint or clicking Insert/Remove Breakpoint button or pressing F9 key on the step.
To enable\disable a breakpoint,i.e enable a checkpoint if disabled below or vice versa, Press Ctrl + F9 or select Debug > Enable/Disable Breakpoint
We can enable disable all breakpoint by selecting Debug > Enable/Disable All Breakpoints or click the Enable/Disable All Breakpoints button.


Debug Viewer in QTP:










We can  use debug Viewer in QTP to view, set, or modify the current value of objects or variables in your test or function library,  To view Debug Viewer, Choose View > Debug Viewer or click the Debug Viewer button.

Below are the tabs in Debug Viewer:


Watch Tab

This is used to view the value of any variable or an expression in the test. To add an expression, Click the expression and choose Debug > Add to Watch.

Variables Tab

QTP automatically displays the current value of all variables in the current action or function in the Variables tab—up to the point where the test or function library is stopped or paused. We can change value of a variable manually also in variables tab. This will be reflected in test.

Command tab

This is to execute a line of script to set or modify the current value of a variable or VBScript object in your test or function library.


How to load and Associate Function libraries in QTP Test at runtime

Below are the various ways by which we can add/associate libraries with QTP tests so that functions in the libraries can be used within test.

ExecuteFile Statement 

      Executes the VBScript statements in the specified file. Functions, subroutines defined in the file are available from the global scope of the action's script.We cannot debug functions or statement contained in the file.

ExecuteFile "C:\BusinessLib.vbs”

Through QTP Interface 

      A library can be associated with a test so that the functions and subroutines, classes defined in the function library can be used .This can be achieved as follows:
      Navigate to File > Settings > Resources > Associate Function Library’ option in QTP. Add the required Libraries to the resources by clicking on + icon.

      Once function library is associated with the test.We can debug function in the function libraries and view function definition of the functions from the scripts.We can also define the priority of function library using up and down icon.

     
Associating Libraries with QTP tests

     

Using Load Function Library method

In  QTP 11, and onwards, We can dynamically load function library with the test using load function library. Libraries are released from test once completed. We can debug into function on calling library using LoadFunctionLibrary. The scope of the library is local to the action in which it is called.

Syntax: LoadFunctionLibrary “D:\TestLib.vbs”


We can add multiple files seperated by


Using Automation Object Model 

We can associate multiple libraries to QTP test using the below code. Also all the tests actions can use the functions from associated libraries.

strFilesNameCommaSeperated = "d:\test1.vbs,d:\test.vbs"
strTestName ="D:\Sample\Test1"
Call LoadLibrariesThroughAOM(strFilesNameCommaSeperated,strTestName)
Public Function LoadLibrariesThroughAOM(strFilesNameCommaSeperated,strTestName)
Set oqtapp = CreateObject("QuickTest.Application")
oqtapp.Launch
oqtapp.Visible = True
 strLibName = split(strFilesNameCommaSeperated,",")
'Open a test and associate a function library to the test
oqtapp.Open strTestName, False, False
Set oLib = oqtapp.Test.Settings.Resources.Libraries
 For i = 0 to ubound(strLibName)
                 LibName = strLibName(i)
                 ' If library is not already added, add the required library.
 
                If oLib.Find(LibName) = -1 Then
                         oLib.Add LibName, 1
                End If
 Next
oqtapp.Test.Save
                End Function


Understanding QTP Automation Object Model

QTP AOM (Automation Object Model) can be used to automate QTP Operations. Using the objects, methods, and properties exposed by the Quick Test automation object model,we can execute script, configure options settings,



Creating the QTP Object


Below lines of codes creates an instance of QTP,launches QTP and makes it visible.
Dim qtApp
Set qtApp = CreateObject("QuickTest.Application")
qtApp.Launch 'Start QTP
qtApp.Visible = True

If we want to execute on a remote computer, we use

Set qtApp = CreateObject("QuickTest.Application",”server”)

If we want to connect to QC from QTP AOM

 qtApp.TDConnection.connect “QC URL”,”Domain”,”Project”,”User”,”Pwd”


Working With QTP Tests using AOM


Open a new Test

Dim qtApp
Set qtApp = CreateObject("QuickTest.Application")
qtApp.Launch 'Start QTP
qtApp.Visible = True
qtApp.New

Opening an Existing Test

qtApp.Open “Test Path”,”True” ‘ Opens in read only mode.

Running a test through AOM

qtApp.Test.Run

Saving a test in QTP

If qtApp.Test.IsNew Then 
        qtApp.Test.SaveAs "C:\QTP\testqtp"
Else
        qtApp.Test.Save
End If

Generating script for QTP Settings and QTP Options for AOM


Set qtResultsOpt = CreateObject("QuickTest.RunResultsOptions") ' Create the Run Results Options object
qtResultsOpt.ResultsLocation =
"C:\Tests\Test1\Res1" ' Set the results location

qtTest.Run qtResultsOpt
Set qtResultsOpt = CreateObject("QuickTest.RunResultsOptions") ' Create the Run Results Options object
qtResultsOpt.ResultsLocation =
"C:\Tests\Test1\Res1" ' Set the results location

qtTest.Run qtResultsOpt

Defining Settings in QTP

To know, how settings are defined and QTP object is launched, and settings are defined using AOM, Go to File>Settings>Properties and click on Generate Script. This will generate a script with all the default setting parameters

Default Setting script


The Content of the script will be as follows:

Dim App 'As Application
Set App = CreateObject("QuickTest.Application")
App.Launch
App.Visible = True
App.Test.Settings.Launchers("Web").Active = False
App.Test.Settings.Launchers("Web").Browser = "IE"
App.Test.Settings.Launchers("Web").Address = "http://www.rediff.com"
App.Test.Settings.Launchers("Web").CloseOnExit = True
App.Test.Settings.Launchers("Windows Applications").Active = True
App.Test.Settings.Launchers("Windows Applications").Applications.RemoveAll
App.Test.Settings.Launchers("Windows Applications").RecordOnQTDescendants = True
App.Test.Settings.Launchers("Windows Applications").RecordOnExplorerDescendants = False
App.Test.Settings.Launchers("Windows Applications").RecordOnSpecifiedApplications = True
App.Test.Settings.Run.IterationMode = "rngAll"
App.Test.Settings.Run.StartIteration = 1
App.Test.Settings.Run.EndIteration = 1
App.Test.Settings.Run.ObjectSyncTimeOut = 20000
App.Test.Settings.Run.DisableSmartIdentification = False
App.Test.Settings.Run.OnError = "Dialog"
App.Test.Settings.Resources.DataTablePath = "<Default>"
App.Test.Settings.Resources.Libraries.RemoveAll
App.Test.Settings.Web.BrowserNavigationTimeout = 60000
App.Test.Settings.Web.ActiveScreenAccess.UserName = ""
App.Test.Settings.Web.ActiveScreenAccess.Password = ""


Defining Options in QTP


To know the current options settings in QTP, we can generate a script similar to Settings as defined above through Tools>Options>General and clicking on generate scripts.


















Dim App 'As Application
Set App = CreateObject("QuickTest.Application")
App.Launch
App.Visible = True
App.Options.DisableVORecognition = False
App.Options.AutoGenerateWith = False
App.Options.WithGenerationLevel = 2
App.Options.TimeToActivateWinAfterPoint = 500
App.Options.SaveLoadAndMonitorData = True
App.Options.Run.RunMode = "Fast"
App.Options.Run.ViewResults = True
App.Options.Run.StepExecutionDelay = 0
App.Options.Run.MovieCaptureForTestResults = "Never"
App.Options.Web.AddToPageLoadTime = 10
App.Options.Web.RecordCoordinates = False
App.Options.Web.RecordMouseDownAndUpAsClick = False
App.Options.Web.RecordAllNavigations = False
App.Options.Web.RecordByWinMouseEvents = ""
App.Options.Web.BrowserCleanup = False
App.Options.Web.RunOnlyClick = False
App.Options.Web.RunMouseByEvents = True
App.Options.Web.RunUsingSourceIndex = True
App.Options.Web.EnableBrowserResize = True
App.Options.Web.PageCreationMode = "URL"
App.Options.Web.CreatePageUsingUserData = "Get Post"
App.Options.Web.CreatePageUsingNonUserData = ""
App.Options.Web.CreatePageUsingAdditionalInfo = True
App.Options.Web.FrameCreationMode = "URL"
App.Options.Web.CreateFrameUsingUserData = "Get Post"
App.Options.Web.CreateFrameUsingNonUserData = ""
App.Options.Web.CreateFrameUsingAdditionalInfo = True
App.Options.WindowsApps.AttachedTextRadius = 35
App.Options.WindowsApps.AttachedTextArea = "TopLeft"
App.Options.WindowsApps.ExpandMenuToRetrieveProperties = True
App.Options.WindowsApps.NonUniqueListItemRecordMode = "ByName"
App.Options.WindowsApps.RecordOwnerDrawnButtonAs = "PushButtons"
App.Options.WindowsApps.ForceEnumChildWindows = 0
App.Options.WindowsApps.ClickEditBeforeSetText = 0
App.Options.WindowsApps.VerifyMenuInitEvent = 0
App.Options.TextRecognitionOrder = "APIThenOCR"
App.Folders.RemoveAll


How to work with Dictionaries using scripting.dictionary object in QTP

Dictionary Object stores data key, item pairs. Each item is associated with a unique key.The key is used to retrieve an individual item and is usually a integer or a string, but can be anything except an array.

Creating a dictionary object:

We can create an instance of dictionary object as shown below:
Set odict = CreateObject("Scripting.Dictionary")
odict.add "country", "India"
odict.add "Capital", "Delhi"  

 
We have created a dictionary object odict, and added 2 key item collection in the dictionary object.
 

Below are the methods of dictionary object:


1.  Add Method - Adds a key and item pair to a Dictionary object.

odict.add "Currency", "Rupee" 


2.  Exists Method - Returns true if a specified key exists in the Dictionary object, false if it does not.

odict.exists(“country”) will return true  for dictionary defined in above examples.



3.  Items Method - Returns an array containing all the items in a Dictionary object.aite = odict.items(“country”)



4.  Keys Method - Returns an array containing all existing keys in a Dictionary object.aite = odict.keys(1)



5.  Remove Method - Removes a key, item pair from a Dictionary object.odict.remove("Currency")



6. RemoveAll Method - The RemoveAll method removes all key, item pairs from a Dictionary object.odict.removeAll()


Properties of Dictionary object

1. Count Property - Returns the number of items in a collection or Dictionary object.Intcount = odict.count


2. Item Property - Sets or returns an item for a specified key in a Dictionary object. For collections, returns an item based on the specified key.ItemVal = odict.Item("Capital")   - gets value of the keyodict.Item("Capital") = “MUMBAI” – sets value of  the key.



3. Key Property - Sets a key in a Dictionary object.odict.Key("Capital") = "City"odict.item(“City”) will now give value of item stored in key Capital before. 


Comparing Dictionaries Vs Arrays


Below is the comparison between array and dictionary objects
  •  Dictionary  has methods to add new items and check for existing items.
  •  On Deleting a particular item from a dictionary, all the subsequent items automatically shift up.
  • You use keys to identify dictionary items. Keys can be any data type while arrays have numeric values as key
  •  A dictionary can't be multidimensional while array can be.
  •  It is much easier to find an item value based on keys as compared to arrays.
  •  Keys in Dictionary can have unique values only
  •  Dictionary can be used as Global variable declaration. so that any test can access the values from it in the run time. Will discuss this in detail in a separate post.

All About Working with datatables and data Sheets in QTP: Methods and properties

Methods for Datatable object


Following are the methods and properties for interaction with data tables in QTP

1. Datatable.AddSheet  

Adds the specified sheet to the run-time Data Table
datatable.AddSheet(strSheetName)

2. DeleteSheet

Deletes the specified sheet from the run-time Data Table.
Datatable.DeleteSheet(strSheetName)

3. Export Method

Saves a copy of the run-time Data Table in the specified location.
datatable.Export(strExcelFile)

4.ExportSheet Method 

Exports a specified sheet of the run-time Data Table to the specified file.
DataTable.ExportSheet(FileName, DTSheet)

5.GetCurrentRow

Returns the current (active) row in the first sheet in the run-time Data Table (global sheet).
row = DataTable.GetCurrentRow

6. GetRowCount Method

Returns the total number of rows in the longest column in the first sheet in the run-time Data Table (global sheet).
DataTable.GetRowCount

7. GetSheet Method:

Returns the specified sheet from the run-time Data Table.
MyParam=DataTable.GetSheet ("MySheet").AddParameter("Rower", "9")

8. GetSheetCount

Returns the total number of sheets in the run-time Data Table.
intSheet = datatable.getSheetCount

9.  Import Method:

 Imports the specified Microsoft Excel file to the run-time Data Table.
DataTable.ImportSheet(FileName, SheetSource, SheetDest)

10. ImportSheetMethod:

Imports a sheet of a specified file to a specified sheet in the run-time Data Table.
DataTable.ImportSheet(FileName, SheetSource, SheetDest)

11.SetCurrentRow Method:

Sets the specified row as the current (active) row in the run-time Data Table.
DataTable.SetCurrentRow(RowNumber)
DataTable.GetSheet("MySheet").SetCurrentRow(2)

12. SetNextRow Method 

Sets the row after the current (active) row as the new current row in the run-time Data Table.
DataTable.SetNextRow
DataTable.GetSheet("MySheet").SetNextRow


13. GlobalSheet Property 

 Returns the first sheet in the run-time Data Table (global sheet).
 DataTable.GlobalSheet.AddParameter "Name", "Nitin"

14. LocalSheet Property

Returns the current (active) local sheet of the run-time Data Table.
DataTable.LocalSheet.AddParameter "Name", "Nitin"


Methods For DTSheet Object:


Below are the methods to work with the specified sheet in datatable.

1. AddParameter Method 

Adds the specified parameter (column) to the sheet in the run-time Data Table, sets the value of the first row to the specified value

DataTable.GetSheet("dtGlobalSheet").AddParameter "Name","Nitin"
DataTable.AddSheet("MySheet").AddParameter("Name", "Nitin")
paramname = DataTable.LocalSheet.AddParameter("Name", "Nitin").Name 

2. DeleteParameter Method

Deletes the specified parameter from the sheet in the run-time Data Table.
DataTable.GetSheet("MySheet").DeleteParameter("Name") 

3. GetCurrentRow Method

Returns the row number of the current (active) row in the run-time Data Table sheet. 
row = DataTable.GetSheet("MySheet").GetCurrentRow 

4. GetParameter Method 

Retrieves the specified parameter from the run-time Data Table sheet. 
DataTable.GetSheet("ActionA").GetParameter("Date").RawValue

GetParameter("ParamName").value retrieves or sets the value of the cell in the current (active) row of the parameter in the run-time Data Table. 
DataTable.GetSheet("Action1").GetParameter("Destination").Value="Pithoragarh"

DataTable.GetSheet("Action1").GetParameter("Destination").ValueByRow(7) - This gets value for parameter Destination in sheet Action 1 in row 7.

5. GetParameterCount Method 

Returns the total number of parameters (columns) in the run-time Data Table sheet.
paramcount = DataTable.GetSheet("Test").GetParameterCount

6. GetRowCount Method

 Returns the total number of rows in the longest column in the run-time Data Table sheet.
 rowcount = DataTable.GetSheet("Test").GetRowCount