Sie sind auf Seite 1von 27

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 object Set myxl = createobject("excel.application") 'To make Excel visible myxl.Application.Visible = true myxl.Workbooks.Add wait 2 'Save the Excel file as qtp.xls myxl.ActiveWorkbook.SaveAs "D:\qtp.xls" 'close Excel myxl.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)=value mysheet.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 state 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") '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 file For i= 1 to Row For j=1 to Col Msgbox mysheet.cells(i,j).value Next Next 'Save the Workbook myxl.ActiveWorkbook.Save 'Close the Workbook myxl.ActiveWorkbook.Close 'Close Excel myxl.Application.Quit Set mysheet =nothing Set myxl = nothing

Compare

Two Excel sheets Cell by cell:

Mismatch=0 Set myxl = createobject("excel.application") 'To make Excel visible myxl.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 Set mysheet1=Workbook1.Worksheets("Sheet1") mysheet2=Workbook2.Worksheets("Sheet1")

'Compare two sheets cell by cell For 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 workbooks Workbook1.close Workbook2.close myxl.Quit set 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 sheet With 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 next End With 'Save the Workbook myxl.ActiveWorkbook.Save 'Close the Workbook myxl.ActiveWorkbook.Close 'Close Excel myxl.Application.Quit Set mysheet =nothing Set myxl = nothing

Copy

an Excel sheet to another Excel sheet:

Set myxl = createobject("excel.application") 'To make Excel visible myxl.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 workbooks Workbook1.save Workbook2.save 'close the workbooks Workbook1.close Workbook2.close myxl.Quit set 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 sheet datatable.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 '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 sheets msgbox 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 Table" . datatable.AddSheet("Qtpworld") 'To delete datatable sheet datatable.DeleteSheet("Qtpworld") datatable.DeleteSheet("Global") wait 3 under section "Run Time data Workbook ,

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 datatable.AddSheet "Sheet1" qtp

'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 sheet datatable.GetSheet("Sheet1").AddParameter "Result","" wait 2 'Apply the logic: "Major" if age is less than 18 then the guy is " Minor" else

row =datatable.GetSheet("Sheet1").GetRowCount For 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 Datatable.ExportSheet "C:\qtpsheet.xls","Sheet1" ' After exporting result excel

you can see that the excel file now has been updated with

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 runtime 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 datasheet row=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 Next "Current Row is: " & datatable.GetSheet("Qtpworld").GetCurrentRow

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 array cnt=0 For iCounter=fStartRange to fEndRange 'Applying the odd number logic : num/2 <>0 then its an odd number If iCounter mod 2<>0 Then ReDim preserve oddNumbers(cnt) ' Storing Odd numbers in dynamic array oddNumbers(cnt)=iCounter cnt=cnt+1 End If Next 'Assigning array to the function fnGetOddNumbersInRange=oddNumbers

End Function '****************************************************** **** '****************************************************** **** 'How to work with this function? 'Here Function will return array value oVal=fnGetOddNumbersInRange(1,10) For i=0 to ubound(oVal) ' Displaying the values in array msgbox 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 function Set QTPObject=Window("Calculator") Call ActivateDialog(QTPObject) 'Create a function to activate calculator Function ActivateDialog(QTPObject) QTPObject.Activate End Function 2nd Type: Calling the function directly passing the object Call ActivateDialog(Window("Calculator")) 'Create a function to activate calculator Function ActivateDialog(QTPObject) QTPObject.Activate

End Function Ex(1)-Consider the example of the actiTime Login age Following 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 If else sMSG="The LoginNow button does not exists" reporter.ReportEvent micFail,"Validation LoginNow",sMSG End 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 QTPobject set QTPobject=Browser("actiTIME - Login").Page("actiTIME - Login").WebButton("Login now") 'The object is set above which is being passed in a function call ValidateExistsAndEnabled(QTPobject) 'The function is called above Function ValidateExistsAndEnabled(QTPobject) sObjectName = QTPobject.Tostring 'Tostring will give the name of the object passed IsExists=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 If

else sMSG=sObjectName&"does not exists" reporter.ReportEvent micFail,"Validation LoginNow",sMSG End 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 bStatus QTPobject.click 'Click if exists and enabled Function ValidateExistsAndEnabled(QTPobject) sObjectName = QTPobject.Tostring IsExists=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 If else sMSG=sObjectName&"does not exists" reporter.ReportEvent micFail,"Validation LoginNow",sMSG End If End Function

Posted by Sachin at 4:40 PM No comments:

Sunday, February 28, 2010


Descriptive 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 application Note: Flight reservation application comes with QTP default Dialog("text:=Login").Activate Dialog("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:=UserName Public const LoginPage_Edit_PassWord = name:=Password Set LoginPage_Button_Login = CreateObjectDescription(name:=Login,type:=submit) ************************************************************ ****** Function CreateObjectDescription(StrProperties) Dim objDescription Dim ObjArr Dim PropCount Dim ObjProperty Set objDescription=Description.Create ObjArr=split(StrProperties,",") For PropCount=0 to ubound(ObjArr) ObjProperty=split(ObjArr(PropCount),":=") objDescri ption(ObjProperty(0)).value=ObjProperty(1) Next Set CreateObjectDescription=objDescription End 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:Acceptable Browser(OR LogicalName).Page(OR LogicalName).Link(name:Login).click Or Browser(OR LogicalName).Page(micclass:Page).Link(name:Login).click Here the hierarchy is Test Object to Descriptive. Browser and page are representing Object Repository names and the link is taking description. Not acceptable Browser(micclass:=Browser).Page(OR LogicalName).Link(name:Login).click Or Browser(micclass:=Browser).Page(micclass:=Page).).Link(OR LogicalName).click This 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 Expressions You 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.* ).Click Ex3: Set oLink = Description.create oLink (name).value= Login.* oLink (index).value= 1 Browser(micclass:=Browser).Page(micclass:=page).Link(oLink).click By default regular expressions for description object is enable. To disable Regular expressions for description object Set oLink = Description.create oLink (name).value= Login.* oLink (name).RegularExpression=False oLink (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 string Set Matches = SampleRegExP.Execute(Hi How Are You) 'Get the results by using a For Loop For Each Match in Matches Msgbox Match.FirstIndex Msgbox Match.Value Next 'Script to extract a substring from a string based upon a pattern match. '*********************************************** * rExpression="H." MainString="Hi How Are You"

Set SampleRegExP = New RegExp SampleRegExP.Pattern= rExpression SampleRegExP.IgnoreCase= False SampleRegExP.Global=True Set Matches = SampleRegExP.Execute(MainString) For Each Match in Matches Msgbox Match.FirstIndex Msgbox Match.Value Next '*********************************************** * '*********************************************** * 'Script to Replace string '*********************************************** * rExpression="H." MainString="Hi How Are You" ReplacedString= "Hello" Set SampleRegExP = New RegExp SampleRegExP.Pattern= rExpression SampleRegExP.IgnoreCase= False SampleRegExP.Global=True Msgbox SampleRegExP.Replace (MainString,ReplacedString) '*********************************************** *

'*********************************************** * 'Script to Test a string existence '*********************************************** * rExpression="H." MainString="Hi How Are You" Set SampleRegExP = New RegExp SampleRegExP.Pattern= rExpression SampleRegExP.IgnoreCase= False SampleRegExP.Global=True retVal = SampleRegExP.Test(MainString) If retVal Then Msgbox "One or more matches were found." Else Msgbox "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. 2. 3. 4. Defects in Application System Environment Issues like Browser is getting closed automatically Application Down for some time 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. 2. 3. 4. Popup Windows (Security Popups) Object State Change (Application Down/ Display of Validation Errors) Script Errors (Due to poor coding) 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. 2. 3. 4. Popup Window Object State Test Run Error 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 Event Popup Window Object State Test Run Error Application Crash Required Details to Specify Window Details Object Details (specify the properties of the object with values) Type of Error Application 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. 2. 3. 4. Keyboard or Mouse Operation Close Application Process Function Call 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. 2. 3. 4. 5. 6. Repeat current step and continue Proceed to next step Proceed to next action or component iteration Proceed to next test iteration Restart current test run 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 Errors Syntax 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 Errors Run Time Errors: Runtime Errors shows when VBScript attempts an action that the system cannot execute. Runtime 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 Errors How 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 Handling You can use this when not using recovery scenarios. view plainprint? 1. 2. 3. 4. 5. 6. 7. 'Clear the error err.clear 'Execute a statement Browser("Google").Page("Google").WebButton("SignIn").click 'Verify error. If error exist, err.number contains a value. Otherwise the value is empty.

8. if err.number<>"" then 9. Reporter.Reportevent micpass,"Button Click", "Clicked on Sign In Button" 10. Else 11. 'Call a recovery function here if needed 12. 'Send error details to result 13. Reporter.Reportevent micfail,"Button Click", "Clicked on Sign In Button Failed"&vbn ewline&"Error Details: "&err.description 14. End If 15. 'Clear the error 16. err.clear 17. 18. 'Execute a statement 19. Browser("Google").Page("Google").WebButton("SignIn").click 20. 21. 'Verify error. If error exist, err.number contains a value. Otherwise the value is empty. 22. if err.number<>"" then 23. Reporter.Reportevent micpass,"Button Click", "Clicked on Sign In Button" 24. Else 25. 'Call a recovery function here if needed 26. 'Send error details to result 27. Reporter.Reportevent micfail,"Button Click", "Clicked on Sign In Button Failed"&vbn ewline&"Error Details: "&err.description 28. 29. 'Clear the error from cache

30. err.clear 31. End If 32. 'Clear the error 33. err.clear 34. 35. 'Execute a statement 36. Browser("Google").Page("Google").WebButton("SignIn").click 37. 38. 'Verify error. If error exist, err.number contains a value. Otherwise the value is empty. 39. if err.number<>"" then 40. Reporter.Reportevent micpass,"Button Click", "Clicked on Sign In Button" 41. Else 42. 'Call a recovery function here if needed 43. 'Send error details to result 44. Reporter.Reportevent micfail,"Button Click", "Clicked on Sign In Button Failed"&vbn ewline&"Error Details: "&err.description 45. End If Why 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 visible

When 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.

Das könnte Ihnen auch gefallen