QTP Excel code

Embed Size (px)

DESCRIPTION

Excel update and data driven code

Citation preview

Excel Automation Object Model

Microsoft has developed the Excel application with heirarachy of object model.We can do excel operations using excel object model.

Simple object model Example: Excel Application --> Workbooks--> Worksheet--> cells

Create an Excel File:'Create a new Microsoft Excel objectSet myxl = createobject("excel.application")

'To make Excel visiblemyxl.Application.Visible = true myxl.Workbooks.Addwait 2

'Save the Excel file as qtp.xlsmyxl.ActiveWorkbook.SaveAs "D:\qtp.xls" 'close Excelmyxl.Application.Quit

Set myxl=nothing

Create an Excel File , Enter some data , Save the Excel and close the Excel:Set myxl = createobject("excel.application")

'Make sure that you have created an excel file before exeuting the script.'Use the path of excel file in the below code'Also make sure that your excel file is in Closed state before exeuting the script.

myxl.Workbooks.Open "D:\qtp.xls" myxl.Application.Visible = true 'this is the name of Sheet in Excel file "qtp.xls" where data needs to be entered set mysheet = myxl.ActiveWorkbook.Worksheets("Sheet1") 'Enter values in Sheet1.'The format of entering values in Excel is excelSheet.Cells(row,column)=valuemysheet.cells(1,1).value ="Name"mysheet.cells(1,2).value ="Age"mysheet.cells(2,1).value ="Ram"mysheet.cells(2,2).value ="20"mysheet.cells(3,1).value ="Raghu"mysheet.cells(3,2).value ="15" 'Save the Workbook

Read the data from Excel File: Set myxl = createobject("excel.application") 'Make sure that you have created an excel file before exeuting the script. 'Use the path of excel file in the below code'Also make sure that your excel file is in Closed statemyxl.Workbooks.Open "D:\qtp.xls" myxl.Application.Visible = true

'this is the name of Sheet in Excel file "qtp.xls" where data needs to be entered set mysheet = myxl.ActiveWorkbook.Worksheets("Sheet1") 'Get the max row occupied in the excel file Row=mysheet.UsedRange.Rows.Count

'Get the max column occupied in the excel file Col=mysheet.UsedRange.columns.count 'To read the data from the entire Excel fileFor i= 1 to Row For j=1 to Col Msgbox mysheet.cells(i,j).value NextNext 'Save the Workbookmyxl.ActiveWorkbook.Save 'Close the Workbookmyxl.ActiveWorkbook.Close 'Close Excelmyxl.Application.Quit Set mysheet =nothingSet myxl = nothing

Compare Two Excel sheets Cell by cell:Mismatch=0Set myxl = createobject("excel.application")

'To make Excel visiblemyxl.Visible = True

'Open a workbook "qtp1.xls"Set Workbook1= myxl.Workbooks.Open("C:\qtp1.xls")

'Open a workbook "qtp2.xls"Set Workbook2= myxl.Workbooks.Open("C:\qtp2.xls") Set mysheet1=Workbook1.Worksheets("Sheet1")Set mysheet2=Workbook2.Worksheets("Sheet1") 'Compare two sheets cell by cellFor Each cell In mysheet1.UsedRange

'Highlights the cell if cell values not match If cell.Value mysheet2.Range(cell.Address).Value Then 'Highlights the cell if cell values not match cell.Interior.ColorIndex = 3 mismatch=1 End If Next If Mismatch=0 Then Msgbox "No Mismach exists"End If 'close the workbooksWorkbook1.closeWorkbook2.close myxl.Quitset myxl=nothing

Search for Particular value in Excel:Set myxl = createobject("excel.application")

'Make sure that you have created an excel file before exeuting the script.'Use the path of excel file in the below code'Also make sure that your excel file is in Closed state before executing the script.

myxl.Workbooks.Open "D:\qtp.xls"myxl.Application.Visible = true 'This is the name of Sheet in Excel file "qtp.xls" where data needs to be entered set mysheet = myxl.ActiveWorkbook.Worksheets("Sheet1") 'Contents of Sheet1'Name Age'Ram 20'Raghu 15 'Select the used range in particular sheetWith mysheet.UsedRange ' Data "Ram" to search' Loop through the used range

For each search_data in mysheet.UsedRange

' compare with the expected data If search_data="Ram" then 'make the cell with color if it finds the data search_data.Interior.ColorIndex = 40 End If nextEnd With 'Save the Workbookmyxl.ActiveWorkbook.Save 'Close the Workbookmyxl.ActiveWorkbook.Close 'Close Excelmyxl.Application.Quit Set mysheet =nothingSet myxl = nothing

Copy an Excel sheet to another Excel sheet:Set myxl = createobject("excel.application")

'To make Excel visiblemyxl.Visible = True

'Open a workbook "qtp1.xls"Set Workbook1= myxl.Workbooks.Open("C:\qtp1.xls")

'Open a workbook "qtp2.xls"Set Workbook2= myxl.Workbooks.Open("C:\qtp2.xls")

'Copy the used range of workbook "qtp1.xls"Workbook1.Worksheets("Sheet1").UsedRange.Copy

'Paste the copied values in above step in the A1 cell of workbook "qtp2.xls"Workbook2.Worksheets("Sheet1").Range("A1").PasteSpecial Paste =xlValues

'Save the workbooksWorkbook1.saveWorkbook2.save 'close the workbooksWorkbook1.closeWorkbook2.close myxl.Quitset myxl=nothing

Addsheet Method:

Description: Adds the specified sheet to the run-time Data Table and returns the sheet so that you can directly set properties of the new sheet in the same statement.

Syntax: DataTable.AddSheet(SheetName)

Example: 'Create a datatable sheet during Run time.This sheet will be available during run time only. 'We can view this sheet in Result Summaryunder section "Run Time data Table".datatable.AddSheet("Qtpworld") 'To add column name and a default value under them.datatable.GetSheet("Qtpworld").AddParameter "name","Ram"

datatable.GetSheet("Qtpworld").AddParameter "age","18" wait 5

DeleteSheet Method:

Description: Deletes the specified sheet from the run-time Data Table.

Syntax: DataTable.DeleteSheet SheetID

Example: 'Create a datatable sheet during Run time.This sheet will be available during run time only. 'We can view this sheet in Result Summary under section "Run Time data Table" .datatable.AddSheet("Qtpworld") 'To delete datatable sheetdatatable.DeleteSheet("Qtpworld")

datatable.DeleteSheet("Global") wait 3

Import Method:

Description: Imports the specified Microsoft Excel file to the run-time Data Table.

Syntax: DataTable.Import(FileName)Example given below

Export Method:

Description: Saves a copy of the run-time Data Table in the specified location.

Syntax: DataTable.Export(FileName) Example:'If data is stored in multiple sheet in external Excel Workbook , 'we can import multiple sheet data into Datatable and 'Do neccessary operation on the imported data.datatable.Import "C:\qtptest.xls"

'To get the total count of QTP datatable sheetsmsgbox datatable.GetSheetCount

'After the operations are done,you can export the all the qtp datasheets to the External file'Create a datatable sheet during Run time.This sheet will be available during run time only. datatable.Export "C:\qtptest.xls"

'We can view this sheet in Result Summary under section "Run Time data Table" .datatable.AddSheet("Qtpworld") 'To delete datatable sheetdatatable.DeleteSheet("Qtpworld")

datatable.DeleteSheet("Global") wait 3

Value Property:

Description: DataTable default property. Retrieves or sets the value of the cell in the specified parameter and the current row of the run-time Data Table.

Syntax: DataTable.Value(ParameterID [, SheetID])

Example given below

ImportSheet Method:

Description: Imports a sheet of a specified file to a specified sheet in the run-time Data Table. The data in the imported sheet replaces the data in the destination sheet (see SheetDest argument).

Syntax: DataTable.ImportSheet(FileName, SheetSource, SheetDest)

Example given below

ExportSheet Method:

Description: Exports a specified sheet of the run-time Data Table to the specified file.

If the specified file does not exist, a new file is created and the specified sheet is saved.If the current file exists, but the file does not contain a sheet with the specified sheet name, the sheet is inserted as the last sheet of the file.If the current file exists and the file contains the specified sheet, the exported sheet overwrites the existing sheet.

Syntax: DataTable.ExportSheet(FileName, DTSheet)

Example: 'If data is stored in a particular sheet in external Excel Workbook , 'we can import only that particular sheet data into Datatable and 'do neccessary operation on the imported data. 'Create a sheet "Sheet1" in qtpdatatable.AddSheet "Sheet1" 'Sheet1 data from excel file contains the following data'Name Age'Ramu 20'Rakesh 24 'Import Sheet1 data from excel file to qtp sheet "Sheet1"datatable.ImportSheet "C:\qtpsheet.xls","Sheet1","Sheet1"

'Add a column "Result" for displaying result in qtp sheetdatatable.GetSheet("Sheet1").AddParameter "Result","" wait 2 'Apply the logic: if age is less than 18 then the guy is " Minor" else "Major" row =datatable.GetSheet("Sheet1").GetRowCountFor i = 1 to row datatable.GetSheet("Sheet1").SetCurrentRow(i) If datatable.Value("Age","Sheet1") > 18 Then datatable.Value("Result","Sheet1") = "Major" Else datatable.Value("Result","Sheet1") = "Minor" End If Next 'Export the qtp sheet "Sheet1" bak to external excel Datatable.ExportSheet "C:\qtpsheet.xls","Sheet1" ' After exporting you can see that the excel file now has been updated with result

GetSheet Method:

Description: Returns the specified sheet from the run-time Data Table.

Syntax: DataTable.GetSheet(SheetID)

Example given below

GetSheetCount Method:

Description: Returns the total number of sheets in the run-time Data Table.

Syntax: DataTable.GetSheetCount

Example given below

GetCurrentRow Method:

Description: Returns the current (active) row in the first sheet in the run-time Data Table (global sheet).

Syntax: DataTable.GetCurrentRow

Example given below

GetRowCount Method:

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

Syntax: DataTable.GetRowCount

Example given below

SetCurrentRow Method:

Description: Sets the specified row as the current (active) row in the run-time Data Table.

Syntax: DataTable.SetCurrentRow(RowNumber)

Example: 'Create a datatable sheet during Run time. 'This sheet will be available during run time only. 'We can view this sheet in Result Summary under section "Run Time data Table" . datatable.AddSheet("Qtpworld")'To add column name and a default value under them. datatable.GetSheet("Qtpworld").AddParameter "name","Ram"datatable.GetSheet("Qtpworld").AddParameter "age","18" 'Enter data into second row of datatsheet "Qtpworld"datatable.GetSheet("Qtpworld").SetCurrentRow(2)datatable.Value("name","Qtpworld")="Ramu" datatable.Value("age","Qtpworld")="23"

'total number of datasheets in the run-time Data Table Msgbox datatable.GetSheetCount 'Get the max used range of the datasheetrow=datatable.GetSheet("Qtpworld").GetRowCount 'Loop to read all the data in the datasheet "Qtpworld" For Drow= 1 to row datatable.GetSheet("Qtpworld").SetCurrentRow(Drow) Msgbox datatable.Value("name","Qtpworld") Msgbox datatable.Value("age","Qtpworld") Msgbox "Current Row is: " & datatable.GetSheet("Qtpworld").GetCurrentRow Next

GlobalSheet Property:

Description: Returns the first sheet in the run-time Data Table (global sheet).

Syntax: DataTable.GlobalSheet

Example given below

LocalSheet Property:

Description: Returns the current (active) local sheet of the run-time Data Table.

Syntax: DataTable.LocalSheet

Example: 'To add column name in Global Sheet and a default value under them.datatable.GlobalSheet.AddParameter "name","ramu"datatable.GlobalSheet.AddParameter "age","18" 'To add column name in Local Sheet and a default value under them.datatable.LocalSheet.AddParameter "name","Rakesh"datatable.LocalSheet.AddParameter "age","22" wait 5

getting more than one value through function

Function fnGetOddNumbersInRange(fStartRange,fEndRange)Dim oddNumbers()Dim cnt,iCounter'Initiating a counter to redim the dynamic arraycnt=0For iCounter=fStartRange to fEndRange'Applying the odd number logic : num/2 0 then its an odd numberIf iCounter mod 20 ThenReDim preserve oddNumbers(cnt)' Storing Odd numbers in dynamic arrayoddNumbers(cnt)=iCountercnt=cnt+1End IfNext'Assigning array to the functionfnGetOddNumbersInRange=oddNumbers End Function'**********************************************************'**********************************************************'How to work with this function?'Here Function will return array valueoVal=fnGetOddNumbersInRange(1,10)For i=0 to ubound(oVal)' Displaying the values in arraymsgbox oVal(i)Next '**********************************************************

Before we start learning AF, We need to know functions.Go through the following example: To activate the calculator using function

1st Type:Store the object in a variable and pass the variable in function

'Object can be passed in a functionSet QTPObject=Window("Calculator")Call ActivateDialog(QTPObject)'Create a function to activate calculatorFunction ActivateDialog(QTPObject)QTPObject.ActivateEnd Function

2nd Type: Calling the function directly passing the object

Call ActivateDialog(Window("Calculator"))'Create a function to activate calculatorFunction ActivateDialog(QTPObject)QTPObject.ActivateEnd Function

Ex(1)-Consider the example of the actiTime Login ageFollowing is example to validate the LoginNow button exist and enabled:Code:(add the object to Object Repository)IsExists=Browser("actiTIME - Login").Page("actiTIME - Login").WebButton("Login now").Exist(2)IsDisabled=Browser("actiTIME - Login").Page("actiTIME - Login").WebButton("Login now").GetROProperty("disabled")

If IsExists Then If IsDisabled Then sMSG="The LoginNow button exists but disabled" reporter.ReportEvent micFail,"Validation LoginNow",sMSG

else sMSG="The LoginNow button exists and enabled" reporter.ReportEvent micPass,"Validation LoginNow",sMSG End Ifelse sMSG="The LoginNow button does not exists" reporter.ReportEvent micFail,"Validation LoginNow",sMSGEnd If

Ex(2)-Above example Ex(1) can be used as a function.'QTPobject can be any object of this page and should be there in object repository'following is the example of login now button passed as QTPobjectset QTPobject=Browser("actiTIME - Login").Page("actiTIME - Login").WebButton("Login now")'The object is set above which is being passed in a functioncall ValidateExistsAndEnabled(QTPobject)'The function is called aboveFunction ValidateExistsAndEnabled(QTPobject)sObjectName = QTPobject.Tostring 'Tostring will give the name of the object passedIsExists=QTPobject.Exist(2)IsDisabled=QTPobject.GetROProperty("disabled")If IsExists Then If IsDisabled Then sMSG=sObjectName&"exists but disabled" 'Tostring will help to display message dynamically without hard coading reporter.ReportEvent micFail,"Validation LoginNow",sMSG

else sMSG=sObjectName&" exists and enabled" reporter.ReportEvent micPass,"Validation LoginNow",sMSG End Ifelse sMSG=sObjectName&"does not exists" reporter.ReportEvent micFail,"Validation LoginNow",sMSGEnd If

End Function

Ex(3)-Validating whether the object exists and enabled, Click if exists and enabled'Continuing from the above example'Pass the object like button as QTPobject and click it set QTPobject=Browser("actiTIME - Open Tasks").Page("actiTIME - Open Tasks").WebButton("Add New Tasks")bStatus=ValidateExistsAndEnabled(QTPobject)if bStatusQTPobject.click 'Click if exists and enabledFunction ValidateExistsAndEnabled(QTPobject)sObjectName = QTPobject.TostringIsExists=QTPobject.Exist(2)IsDisabled=QTPobject.GetROProperty("disabled")If IsExists Then If IsDisabled Then sMSG=sObjectName&"exists but disabled" reporter.ReportEvent micFail,"Validation LoginNow",sMSG

else sMSG=sObjectName&" exists and enabled" reporter.ReportEvent micPass,"Validation LoginNow",sMSG End Ifelse sMSG=sObjectName&"does not exists" reporter.ReportEvent micFail,"Validation LoginNow",sMSGEnd If

End Function

Posted by Sachin at 4:40 PM No comments: Sunday, February 28, 2010Descriptive Programming Descriptive Programming: This is to write and run a QTP script without adding objects in object repository

Ex(1): Write a DP script to log into Flight reservation applicationNote: Flight reservation application comes with QTP default

Dialog("text:=Login").ActivateDialog("text:=Login").WinEdit("Attached text:=Agent Name:").Set"aaaaa"Dialog("text:=Login").WinEdit("Attached text:=Password:").Set"mercury"Dialog("text:=Login").Winbutton("text:=ok").Click

Explaination:Consider the above example, The objects are identified with the properties and values in QTP(By physical description)In Dialog("text:=Login"), text is a property and Login is a value. same way for WinEdit("Attached text:=Agent Name:"), Attached text is a property and Agent Name is a value

Solution:Public const LoginPage_Edit_UserName = name:=UserNamePublic const LoginPage_Edit_PassWord = name:=PasswordSet LoginPage_Button_Login = CreateObjectDescription(name:=Login,type:=submit)

******************************************************************Function CreateObjectDescription(StrProperties)Dim objDescriptionDim ObjArrDim PropCountDim ObjPropertySet objDescription=Description.CreateObjArr=split(StrProperties,",")For PropCount=0 to ubound(ObjArr) ObjProperty=split(ObjArr(PropCount),":=") objDescription(ObjProperty(0)).value=ObjProperty(1)NextSet CreateObjectDescription=objDescriptionEnd Function******************************************************************This function gives a way to use multiple properties for any number of objects with less code maintenance. But the only one rule is we need follow is set statement. Because the return value of the function CreateObjectDescription is a description object. To store any object in a variable we need to use Set statement.The parameter which you pass to the function should be in string format.

EX: Set LoginPage_Button_Login = CreateObjectDescription(name:=Login,type:=submit)

Can I Use the combination of Object Repository and Descriptive programming in a statement?Yes. But the hierarchy must be in Test Object to Descriptive.

Ex:AcceptableBrowser(OR LogicalName).Page(OR LogicalName).Link(name:Login).clickOrBrowser(OR LogicalName).Page(micclass:Page).Link(name:Login).clickHere the hierarchy is Test Object to Descriptive. Browser and page are representing Object Repository names and the link is taking description.

Not acceptableBrowser(micclass:=Browser).Page(OR LogicalName).Link(name:Login).clickOrBrowser(micclass:=Browser).Page(micclass:=Page).).Link(OR LogicalName).clickThis means that from the point where you have started giving description to the objects in a statement, you must continue giving description to the total objects in that hierarchy.

Using Regular ExpressionsYou can directly use regular expressions in the properties.Ex1:Public const LoginPage_Edit_UserName = name:=UserName.*Ex2:Browser(micclass:=Browser).Page(micclass:=page).Link(name:=Login.*).ClickEx3:Set oLink = Description.createoLink (name).value= Login.*oLink (index).value= 1Browser(micclass:=Browser).Page(micclass:=page).Link(oLink).clickBy default regular expressions for description object is enable. To disable Regular expressions for description objectSet oLink = Description.createoLink (name).value= Login.*oLink (name).RegularExpression=FalseoLink (index).value= 1

Using Regular Expressions in Scripting Techniques'To use Regular Expressions in scripting first we should create Instance of Regular Expression Class. Set SampleRegExP = New RegExp 'Set the Search Pattern (Regular Expression) SampleRegExP.Pattern= H.* 'Specify the Case Sensitivity is true or false SampleRegExP.IgnoreCase= False 'Specify required search results (True is for all search Results, False is for only one) SampleRegExP.Global=True 'Execute Search conditions on a main stringSet Matches = SampleRegExP.Execute(Hi How Are You) 'Get the results by using a For LoopFor Each Match in MatchesMsgbox Match.FirstIndexMsgbox Match.ValueNext'Script to extract a substring from a string based upon a pattern match.'************************************************rExpression="H."MainString="Hi How Are You" Set SampleRegExP = New RegExpSampleRegExP.Pattern= rExpressionSampleRegExP.IgnoreCase= FalseSampleRegExP.Global=TrueSet Matches = SampleRegExP.Execute(MainString) For Each Match in MatchesMsgbox Match.FirstIndexMsgbox Match.ValueNext'************************************************'************************************************'Script to Replace string'************************************************rExpression="H."MainString="Hi How Are You"ReplacedString= "Hello"Set SampleRegExP = New RegExpSampleRegExP.Pattern= rExpressionSampleRegExP.IgnoreCase= FalseSampleRegExP.Global=True Msgbox SampleRegExP.Replace (MainString,ReplacedString)'************************************************'************************************************'Script to Test a string existence'************************************************rExpression="H."MainString="Hi How Are You" Set SampleRegExP = New RegExpSampleRegExP.Pattern= rExpressionSampleRegExP.IgnoreCase= FalseSampleRegExP.Global=True retVal = SampleRegExP.Test(MainString)If retVal ThenMsgbox "One or more matches were found."ElseMsgbox "No match was found."End If '******************************************

Error Handling and Recovery Scenarios in QTP - Part-1 Error Handling and Recovery Scenarios in QTP - Part-1 Introduction Just think What type of errors/blockers we get when testing an application? (in Manual Testing) 1. Defects in Application 2. System Environment Issues like Browser is getting closed automatically 3. Application Down for some time 4. Unexpected Popup Windows which are not documented in Testcase These are some sample issues in manual testing. What will a manual tester do in above situations? Simple. He will use some sense. If there are defects, He will stop executing that testcase and reports it. If browser got closed He will reopen the browser and continues the execution. If application is down, He will stop executing the testcases. He will take the required action for Popup windows. He can do because he can change his mind dynamically. When it comes to Automation, the script will play the role of manual tester. But the Automation Tester should provide enough intelligence to the script to handle above errors like the way how those handled manually. To provide that strength to the script, Automation Tester will use VB Script Err Object and Recovery Scenarios. So what type of errors we get when executing a script? 1. Popup Windows (Security Popups) 2. Object State Change (Application Down/ Display of Validation Errors) 3. Script Errors (Due to poor coding) 4. Sudden Death of Application (Computer Problem/OS Problem) How Recovery Scenarios will provide strength to Script? Recovery Scenarios are useful to continue the execution when it is interrupted by any unexpected event/error. When error occurs, the error information will be collected by QTP Recovery Mechanism and a predefine recovery scenario will be executed to overcome the error and to continue the execution. The predefined recovery scenarios will be developed by the Automation Tester. A Recovery Scenario consists of 3 sections 1. Type of Error 2. What is the operation you want to perform (To Overcome the Error) 3. What do you want to do after performing the operation (To Continue the execution) The Automation Tester will think of every possible error that might occur in execution time and prepares recovery scenarios for them as per the above model and associate them in Test Settings of QTP Test.

Figure 1: Associated Recovery Scenarios When execution got interrupted due to an error, QTP applies the specified Recovery Scenarios as per the prioritization. The Recovery Operation will be executed when the error details specified in Recovery Scenario got matched with the error that is caused interruption to the execution. How to Define a Recovery Scenario? Technically the above 3 sections are called as below 1. Trigger Event 2. Recovery Operation 3. Post Recovery Operation Trigger Event: The type of event that is causing interruption to the execution. Type of Trigger Events: 1. Popup Window 2. Object State 3. Test Run Error 4. Application Crash

Figure 2: Trigger Events The below information is required for each trigger event. This information will be used to match the errors that are occurred in execution time. Trigger EventRequired Details to Specify

Popup WindowWindow Details

Object StateObject Details (specify the properties of the object with values)

Test Run ErrorType of Error

Application CrashApplication Process Name

Recovery Operation: The operations that are required to clear the errors/blockers that are interrupted the execution. The Recovery Operation will be executed only when Trigger Details and Error details are matched. The below recovery operations available in QTP 1. Keyboard or Mouse Operation 2. Close Application Process 3. Function Call 4. Restart Microsoft Windows

Figure 3: Recovery Operations Keyboard or Mouse Operation A Keyboard stroke/ Mouse click will be performed. It will be used when there is only one step operation is required. Ex: Click a button Close Application Process The specified process will be closed. It will be used when any other application is interrupting execution. Ex: An antivirus system blocking execution. Function Call A library function will be called. It will be used when there are multiple steps need to be executed. Ex: When providing functional alternative, When you want to analyze the error and perform operation Restart Microsoft Windows QTP Restarts the Operating System. This will be used when the execution blocked because of a pending restart. Post Recovery Operations: Recovery Operation used to clear the errors/blockers of execution. But Post Recovery Operations provide a facility on how you want to continue the execution after performing the Recovery Operation. The below are Post Recovery Operations 1. Repeat current step and continue 2. Proceed to next step 3. Proceed to next action or component iteration 4. Proceed to next test iteration 5. Restart current test run 6. Stop the test run

Figure 4: Post Recovery Operations Why Post Recovery Operations are required? What will happen when an Application got crashed? We will reopen the application. But how the execution will be continued? If 50 steps are executed for a script, How recovery operation will execute those 50 steps and continues the execution. No way. This type of cases we just use Restart Current Test Run as Post Recovery Operation. So Post Recovery Operations are useful to continue the execution based on the performed Recovery Operation. Its also useful to quit the execution in proper way. Repeat Current Step and Continue By default Recovery Scenarios will be executed when execution got interrupted due to an error. There is a facility to execute recovery scenarios for each step. I.e. whether you get error or not Recovery Scenarios will be executed. Executing them for each step will make low performance for the script and hence by default the Recovery Scenarios will be activated on error (Observe Figure1). QTP understands that there is an error only when a step got failed. If that is important step and recovery operation is covering it then we choose Repeat Current Step and Continue option. Ex: Login button got disabled QTP tries to click on it and failed. Recovery operation did something to enable Login button. QTP already executed clicking on Login button and it will try to execute next step which will become fail. In this case Repeat Current Step and Continue will make QTP to re-execute the clicking on login button step. Proceed to Next Step If the failed is not important or if Recovery Operation completely clears the way for execution then this option will be useful. Proceed to next Action or Component Iteration Exit from current Action iteration and starts executing next Iteration. This will be used when a Test is using Actions concept and you want to skip the only that Action iteration execution. This option is useful to execute the same Action with next set of data that is available in datatable. Component is the concept of BPT (Business Process Test). Proceed to next Test Iteration Exit from current Test iteration and starts executing next Iteration. This option is useful to execute the same Test with next set of data that is available in datatable. The above two are based Iterations concept. Please go thru below link to understand Test/Action Iterations. http://www.qtpsudhakar.com/2009/07/test-action-iterations.html. Restart current test run Restart the current Test Run. This option is used when there is the functional flow got disturbed and not able to continue the execution. Stop the Test Run Stops running that Test. This will be used when application is down or an open defect still there and no need to continue the execution of that test. Error Handling and Recovery Scenarios in QTP - Part-2 VBScript Error Handlers In Part-1 we have discussed about Recovery Scenario and now we know that Recovery Scenarios are useful to continue the script execution whenever an error/exception/unexpected event interrupts the script execution. But Recovery Scenarios will not handle VBScript Errors. It can only handle QTP Errors. What is an error in VBScript? When working with VBScript you get two types of errors. 1. Syntax Errors 2. Runtime ErrorsSyntax Errors:Syntax error is a grammatical mistake. In that case VBScript compiler doesnt understand your statement and throws an error. It can be found in compilation stage before the script has begun to be executed. Ex: calling a sub with parenthesis (.You can find the list of syntax errors in QTP Help File (Press F1 to get) > VBScript Reference > VBScript > VBScript Language Reference > Errors (VBScript) > VBScript Syntax ErrorsRun Time Errors:Runtime Errors shows when VBScript attempts an action that the system cannot execute. Run-time errors occur in script execution time when variable expressions are being evaluated, and memory is being dynamic allocated. Ex: When calling a function which is not there/loaded, When assigning values to an array more than allocated size.You can find the list of syntax errors in QTP Help File (Press F1 to get) > VBScript Reference > VBScript > VBScript Language Reference > Errors (VBScript) > VBScript Runtime ErrorsHow to handle VBScript Errors?You cannot skip from syntax errors. You must fix them in order to start execution. There is no specific recovery mechanism for VBScript runtime errors. But you can suppress them.On Error Resume Next: This statement will simply suppress the errors and executes entire script. Suppressing the error means when error occur VBScript shows popup error message, pauses execution and waits for user action. When using this statement, the error popup will not be displayed on failure and goes to the next statement for execution.On Error Go to 0: This statement is used to disable On Error Resume Next.In VBScript there is no facility to call a statement/function on error. But you can use err object to perform condition based error handling. On Error Resume Next, Go to 0 and Err objects will work for VBScript as well as for QTP Objects.Err Object: This object captures the information about runtime errors. Using this you can always get the last error details. To access error details you can use err.number or err.description statements. We can clear and raise the runtime errors using this object.Condition Based Error HandlingYou can use this when not using recovery scenarios.view plainprint?1. 'Cleartheerror2. err.clear3. 4. 'Executeastatement5. Browser("Google").Page("Google").WebButton("SignIn").click6. 7. 'Verifyerror.Iferrorexist,err.numbercontainsavalue.Otherwisethevalueisempty.8. iferr.number""then9. Reporter.Reporteventmicpass,"ButtonClick","ClickedonSignInButton"10. Else11. 'Callarecoveryfunctionhereifneeded12. 'Senderrordetailstoresult13. Reporter.Reporteventmicfail,"ButtonClick","ClickedonSignInButtonFailed"&vbnewline&"ErrorDetails:"&err.description14. EndIf15. 'Cleartheerror16. err.clear17. 18. 'Executeastatement19. Browser("Google").Page("Google").WebButton("SignIn").click20. 21. 'Verifyerror.Iferrorexist,err.numbercontainsavalue.Otherwisethevalueisempty.22. iferr.number""then23. Reporter.Reporteventmicpass,"ButtonClick","ClickedonSignInButton"24. Else25. 'Callarecoveryfunctionhereifneeded26. 'Senderrordetailstoresult27. Reporter.Reporteventmicfail,"ButtonClick","ClickedonSignInButtonFailed"&vbnewline&"ErrorDetails:"&err.description28. 29. 'Cleartheerrorfromcache30. err.clear31. EndIf32. 'Cleartheerror33. err.clear34. 35. 'Executeastatement36. Browser("Google").Page("Google").WebButton("SignIn").click37. 38. 'Verifyerror.Iferrorexist,err.numbercontainsavalue.Otherwisethevalueisempty.39. iferr.number""then40. Reporter.Reporteventmicpass,"ButtonClick","ClickedonSignInButton"41. Else42. 'Callarecoveryfunctionhereifneeded43. 'Senderrordetailstoresult44. Reporter.Reporteventmicfail,"ButtonClick","ClickedonSignInButtonFailed"&vbnewline&"ErrorDetails:"&err.description45. EndIfWhy VBScript Errors cannot be handled by Recovery Scenario Manager?QTP is having a large set of Objects, Methods, Properties, statements and Keywords that are not available in VBScript. But to access QTP objects/methods/properties/statements/keywords we must use the standards of VBScript. QTP Recovery Scenario Manager is developed to handle the issues that are occurred when working with QTP Test objects. So Recovery Scenario Manager works only with the errors that are related Test Objects and It cannot handle any other errors.QTP activate Recovery Scenarios only on below errors. Whether it is Popup/Object State/TestRun Error/Application crash QTP gets any of the below error and activates the Recovery Scenario Mechanism. Object Not Found Item in list or menu is not unique Item in list or menu not found More than one object responds to the physical description Object is disabled Object not found Object not visibleWhen to use Recovery Scenario Manager and VBScript Error Handlers?Recovery Scenario Manager useful to handle the test object related errors and VBScript error handlers useful to handle VBScript runtime errors. We must use both in order to complete the execution.