View
226
Download
0
Category
Preview:
Citation preview
7/30/2019 QTP Class Notes 1
1/82
Nagesh_rao46@yahoo.com Automation Testing
Jai Sri Ram Jai Sai Ram
Nagesh Sir Class Notes
AUTOMATION TESTING
MANUAL TESTING
Testing an application with human interaction is called Manual Testing.
Drawbacks of Manual Testing
(i) Time consuming.(ii) More resources required.(iii) Human Errors(iv) Repetition of the Task is not much(v) Tiredness(vi) Simultaneous auctions are not possible (Parallel)
Automation Testing
Testing an application with 3rd
Party Software help is called Automation
Testing.(or)
Testing an application with an Automation Tool is also called asAutomation Testing.
Benefits of Automation Testing:
a) Fast
b) Reliable
c) Repeatable
d) Reusable
e) Comprehensive
f) Programmable.
a) Fast
Automation tool runs tests significantly more faster than humanusers.
b) Reliable
Automation tool can perform the same operation each time, if you
repeated multiple times, so that we can eliminate human errors.
c) Repeatable
We can check how application or website reacts after repeated the
same operation with multiple times.
mailto:Nagesh_rao46@yahoo.commailto:Nagesh_rao46@yahoo.com7/30/2019 QTP Class Notes 1
2/82
Nagesh_rao46@yahoo.com Automation Testing
d) Reusable
Automation scripts are reusable on different version of the
application of websites even if the user interfaces changes.
e) Comprehensive
In automation testing we can build a suit of tests that covers everyfeature in the application or website.
f) Programmable.
We can program sophisticated Tests that bring out hidden
information from the application.
Drawbacks of Automation Testing
1) It is expensive
2) We cannot automate all areas.3) Lack of expertisation.4) It has some limitations (It cannot test every thing)
Which Software Testing should be automated?
Tests that need to be execute of every build of the application (SanityTesting)Tests that use multiple data values (Retesting / Data Drives Testing)
Tests that required data from application intimates (G.U.I. Attributes)
Load and Stress Testing
Which Software Testing should not be automated?
Usability TestingOne time testingQuick look Tests or A.S.A.P (As soon as possible) TestingAd-hoc testing / Random TestingCustomers requirement are frequently changing.
Type of Tools
Generally they are (4) Types of tools are available in the market. They are1) Functional Tools:
QTP, WinRunner, Silktest, Rational Robot, TestPartner, etc.,2) Performance Tools:
LoadRunner, J-Meter etc.,3) Test Management Tools:
Quality Center (QC), Test Director.4) Version Control Tools
VSS (Visual Safe Source), PVCS (Polytron Version Control System) etc.,
7/30/2019 QTP Class Notes 1
3/82
QUICKTEST PROFESSIONAL
QTP is a Functionality Testing Tool developed by Mercury Interactivelater merged with HP
QTP has released in following Versions.5.5 6.5 8.0 8.2 9.0 9.1 9.2
9.5 (Latest)License
They are Two types of licenses (1) Seat License (Single User) and (2)
Concurrent License (Multiple Users).
Technologies
QTP 9.2 Supports following Technologies
.Net, VB, JAVA, ActiveX Controls, Web Servers, People Soft, SAP,
Oracle, Terminal Emulators, HTML, DHTML, XML .. etc.,
QTP 9.5 Supports following Technologies
Power Builder, Oracle Forms10, Apps 12, New Terminal Emulator
Versions (Mainframe Application Technologies), .Net (3.5)
Environments
QTP 9.2 Support on following Environment
Windows 2000 Server, 2000 Professional, 2003 Server, XP etc.,QTP 9.5 Support on following Environment
Windows Vista (64 Bit), Eclipse (3.2 & 3.3), Netscape 9.0, Firefox (3.0)
Note
QTP does not support on Linux / Unix Operating Systems. X-Runnersupports on Linux / Unix Operating System.QTP can support client / Server, Web Applications.QTP Records the business operations in VB Script (It can also supportJAVA Script)QTP can support Multimedia Applications such as Flash, Windows
Media Player, Real Video etc.,
7/30/2019 QTP Class Notes 1
4/82
How to Launch QTP (9.2)
Start Programs QuickTest Professional QuickTest Professional
Select Specified Add-in Manager Ok
Apart from the 3 Options, QTP
supports standard windows Environment
(When we uncheck the above 3 Options)
Prepare to Record
Recording
Editing
Debugging
Running
Analyze Results
QTP (9.2) TESTING PROCESS
Context Sensitive Mode / Standard Mode
(Default)
Analog Recording Mode
Low Level Recording Mode
Standard Checkpoint
Bitmap Checkpoint
Database Checkpoint
Text Checkpoint
Text Area Checkpoint
Page Checkpoint
Table Checkpoint
Image Checkpoint
Accessibility Checkpoint
XML Checkpoint
Verify Mode (Default)
Update Run Mode
Debugging Mode
Defect Report
7/30/2019 QTP Class Notes 1
5/82
Recording Modes
In QTP, there are (3) Recording Modes such as
1) Context Sensitive Mode
In this mode QTP Records the operations which are performed onthe objects. Context Sensitive Mode is also called as Standard RecordingMode / Normal Recording Mode.
Context Sensitive Mode is default Recording Mode in QTP.
2) Analog Recording Mode
In this mode QTP records the Mouse and Keyboard Operationswith respective to Window (or) Desktop co-ordinates.
Syntax: If you take Desktop Coordinates Desktop
Desktop.RunAnalog ""Window Window("Window_Name").RunAnalog ""
Navigation
Start Recording (F3) Automation Menu Analog Recording
Analog Recording Settings (Shift + Alt + F3)
Click on Click on Start Analog Record Record your required
Operation Stop Recording (F4)
Generally we are using Analog Recording Mode to compare Digital
Signatures, Barcodes, Scientific Graphs etc.,
Note
In Context Sensitive Mode, QTP Generate one statement for eachoperation. But in Analog Recording Mode, QTP Generates singlestatement for all the operations which you perform on the application.In Analog Recording Mode, if you take Desktop Co-ordinates, you canget wrong output, if application is moved from one place to another
place at Run Time.If you take Window co-ordinates, we can get right output even if the
application moved from one place to another place.
7/30/2019 QTP Class Notes 1
6/82
3)Low Level Recording Mode
We can use this mode to records the operations which are not recognizedby Tool.
Navigation
Start Recording (F3) Automation Menu Low Level RecordingMode (Crtl + Shift + F3) Record your required Operation StopRecording (F4)
Note: We are giving low priority to this recording mode.
Important Note
If you want to select Analog Recording Mode or Low Level Recording
Mode you must be under Context Sensitive Mode.
Running Modes
There are (3) Running Modes such as (1) Verify Mode (2) Update Run Mode
(3) Debugging
1) Verify Mode
To compare expected value with Actual value and Return results.
2) Update Run Mode
To update Test or Component.
3) Debugging
Whether the script is smoothly executing or not without any
interruptions.
Note
Verify Mode is the default Running Mode in QTP. Maintenance
Run Mode is the extra Run Mode in QTP 9.5 than 9.2.
Window / Object Script
Main Window Window(Window_Name)
Sub Window Dialog (Window_Name)
Edit Box WinEdit(EditBox Name)
Combo Box WinCombo(ComboBox Name)Menu WinMenu (Menu)
Radio Button WinRadioButton(Radio Button Name)
Check Box WinCheckBox(Check Box Name)
Push Button WinButton(Push Button Name)
7/30/2019 QTP Class Notes 1
7/82
Note
Environment Class Name
Visual Basic VBButton
JAVA JAVAButton
Web WebButtonActiveX ACXButton
.Net SWFButton(Shock Wave Flash)
Standard Window WinButton
Operations Script
Active Window .Activate
Enter Text in Edit Box .Set "Text"
Select Item from the Combo Box .Select "Item Name"
Select item from the Menu .Select "Menu_Name;Item_Name"Check on or off the Radio Button .Set
Check on or off the Check Box .Set On/Off
Press on Push Button .Click
Enter Password in Edit Box .SetSecure "Encrypted_Text"
Windows Based
In which window.on what object.what operation is done.Syntax:Window(Window_Name).Object(Object_Name).Operation/Method.
Web BasedIn which browser.in which page.on what object.what operation is done. Syntax:
Browser(Browser_Text_Name).Page(Page_Name).Object(Object_Name)
.Operation/Method.Example-1:
Expected:
Activate Window. Enter Employee Name as Appa Rao. Enter Employee No. as E001
Enter Employee Salary as 10000 Click on Submit
Script
Window("Employee").Activate Window("Employee").WinEdit("Employee Name:").Set "Appa Rao" Window("Employee").WinComboBox("Employee No:").Select "E001" Window("Employee").WinEdit("Employee Salary:").Set "10000" Window("Employee").WinButton("Submit").Click
7/30/2019 QTP Class Notes 1
8/82
Ex-2:
Expected:
Activate Window.
Enter Agent Name as Apparao
Enter Password as mercury
Click on Ok
Script
Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set "Apparao" Dialog("Login").WinEdit("Password:").SetSecure "492555ba0ee4f4f47004a1821cb87f8cc8ffe920"
Dialog("Login").WinButton("OK").Click
Ex-3:
Expected
Activate Window. Enter Patient Name as XYZ Select Ward No. as 101 Select Referral Doctor as Dr.John
Cough Radio Button ON Bill Check Box ON Click Ok Enter X-Ray cost as 200 Enter Blood Test as 300 Enter Bed Bill as 500 Click Ok.
7/30/2019 QTP Class Notes 1
9/82
Script
Window("KeyClinic").ActivateWindow("KeyClinic").WinEdit("Patient Name:").Set "XYZ"Window("KeyClinic").WinComboBox("Ward No:").Select "101"Window("KeyClinic").WinComboBox("Referral Doctor:").Select "Dr.John"Window("KeyClinic").WinRadioButton("Cough").SetWindow("KeyClinic").WinCheckBox("Bill").Set "ON"Window("KeyClinic").WinButton("Ok").ClickWindow("KeyClinic").Dialog("Bill").WinEdit("X-Ray:").Set "200"Window("KeyClinic").Dialog("Bill").WinEdit("Blood Test:").Set "300"Window("KeyClinic").Dialog("Bill").WinEdit("Bed Bill:").Set "500"Window("KeyClinic").Dialog("Bill").WinButton("Ok").Click
Ex-4
Expected
Click Ok
Script
Window("SAMPLE").Dialog("SAMPLE-1").Dialog("SAMPLE-2").WinButton("Ok").Click
Ex-5
Expected Enter Branch Name as Ameerpet Enter Address as Ameerpet. Enter ZIP Code as 500016 Select Country as India Select State as Andhra Pradesh
Select City as Hyderabad.
Script
Browser("AXIN BANK").Page(AXIN BANK).WebEdit("BranchName").Set "Ameerpet"
Browser("AXIN BANK").Page(AXIN BANK).WebEdit("Address").Set
"Ameerpet"
Automation Testing 9
7/30/2019 QTP Class Notes 1
10/82
Browser("AXIN BANK").Page(AXIN BANK).WebEdit("ZIPCode").Set "500016"
Browser("AXIN BANK").Page(AXIN BANK).WebList("Country").Select "India"
Browser("AXIN BANK").Page(AXIN BANK).WebList("State").Select"Andhra Pradesh" Browser("AXIN BANK").Page(AXIN BANK).WebList("City").Select
"Hyderabad"
Browser("AXIN BANK").Page(AXIN BANK).WebButton("Submit").
Click
Ex-6
Expected
Enter Agent Name as John Enter Password as mercury Click on Login
Script
Browser("Rediff Shopping").Page(RediffShopping).WebEdit("Agent Name").Set John
Browser("Rediff Shopping").Page(Rediff
Shopping).WebEdit("Password").SetSecure492b7106207d6db37e2a339047b52e9d09b8ed48
Browser("Rediff Shopping").Page(Rediff
Shopping).Image("Login").Click
7/30/2019 QTP Class Notes 1
11/82
Architecture of QTP Screen
Data
Table
Test Pane
Active
Screen
InformationPane
Missing
Resources
Pane
1) Test Pane
In this QTP displays the Test Script which yourecord on the application.
To view the Test scripts, there are two modes suchas (i) Keyword View (ii) Expert View.(i) Keyword View
In this mode QTP displays the test script in
object hierarchy way and it providesdocumentation for every operation.
There are (4) Parts (i) Item (ii) Operation
(iii) Value (iv)Documentation likes as below.
(ii) Expert View
In this mode QTP displays the Test script in VB Script.
7/30/2019 QTP Class Notes 1
12/82
It is used to store the data and parameterize that data to the test script There are (2) Sheets by default. They are (1) Global (2) Action1 In one data table we will have 256 Sheets. Out of 256 sheets, one sheet
is Global and remaining 255 sheets are Action Sheets
Global Sheet related to all the tests.
Action Sheet related to corresponding Action only.
3) Active Screen
In this QTP captures window snapshots for every object operationsand displays those images in Active Screen Area.Advantages
i) Easy to insert Check Pointsii) Easy to insert Output values.iii)Easy to add objects to all object repository.
iv)Easy to insert steps.v) Easy to understand script by observing images in active screen areaDisadvantages
It occupies lot of space to store the snapshots.
To disable Active Screen
Tools Options Active Screen Tab Custom Level under
Windows applications Select None under Web select Disable
Active Screen capture Ok Ok
4) Debug Viewer
It is used for viewing, modifying or setting the current values ofvariables or objects during Test execution break with the help of 3Options, such as (i) Watch (ii) Variables (iii) Command.
5) Information Pane
It displays the syntax of related information during Check Syntax
Syntax Check (Ctrl + F7)
6) Missing Resources Pane
Whenever we open a test, the files which are associated with thattest are missed / moved, then Missing Resources Pane will be openedautomatically and displays the information about that missed file.
7/30/2019 QTP Class Notes 1
13/82
CHECKPOINTS
1) Standard Check Point
We can use this check point to verify the property of an object.Ex: Verify Update Order
Step Name Step description Expected result Actual Status
Step-1 Activate Window DisableStep-2 Open Record Disable
Step-3 Perform change Enable
Navigation
Start Recording Click on Ok Activate Window (Flight 4a.exe) File
Menu Click on Open Order Select Order No. Enter No. Click on Ok
Perform any changeClick Update Order Stop
RecordingKeep theapplication (Flight4a.exe) in base state Identify
positions in the Test Script to insert Check Points [After Activate window; afteropen order; after perform change] Start Recording {Insert Menu Check
Points Click on
Standard Check Point} {or F12} show object [ ] with Click Ok EnterName of the Check Point Select Property with expected value (Enable-True= Enable; Enable-False = Disable) Click Ok Stop Recording afterinsertion of all Check points at relevant places Click Run Analyzeresults manually.
Ex:1Window("Flight Reservation").ActivateWindow("Flight Reservation").WinButton("Update Order").Check CheckPoint("CP_1")Window("Flight Reservation").WinMenu("Menu").Select "File;Open Order..."Window("Flight Reservation").WinButton("Update Order").Check CheckPoint("CP_2")Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set"ON" Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set "30"Window("Flight Reservation").Dialog("Open Order").WinButton("OK").ClickWindow("Flight Reservation").WinRadioButton("Economy").Set Window("FlightReservation").WinButton("Update Order").Check CheckPoint("CP_3") Window("Flight
Reservation").WinButton("Update Order").Clickwait (10)If Window("Flight Reservation").ActiveX("Threed Panel Control").GetROProperty("text")="Update Done..." Then
msgbox ("Test is pass")else
msgbox ("Test is fail")End If
Run in Update Run Mode
7/30/2019 QTP Class Notes 1
14/82
How to edit existing check point:
Place the cursor on Check Point which you want to edit Right ClickCheck Point Properties Select property Change value or Rename CheckPoint Click Ok.
How to insert check point through Active Screen
Start Recording Record Required Operation like as below [Click on Ok Activate Window (Flight 4a.exe) File Menu Click on Open Order Select Order No. Enter No. Click on Ok Perform any change ClickUpdate Order] Stop Recording Keep the application (Flight4a.exe) in basestate Identify positions in the Test Script to insert Check Points [AfterActivate window; after open order; after perform change] place the cursor on
specified statement Click on Active Window Right Click on object Click on Insert Standard Check Point Click Ok Enter Check Point Name Select Property with expected value (Enable-True = Enable; Enable-False=Disable) Select option to insert statement (Before current Step / Aftercurrent Step) Click Ok Click Run after insertion of all Check points atrelevant places Analyze results manually.
2) Bit Map Check Point
We can use this Check Point to conduct test on Bitmaps.Navigation
Start Recording Help Menu Click on about Insert Menu (QTP) Check Point Click Bit Map Check Point Show Bitmap with hand icon
Click Ok Enter Name of the Check Point Click on select area if youwant to check a specific area with in the Bit Map Select save only selectedarea Click on Ok Stop Recording Close current application (Flight 4a) Open another application (Flight 4b) Click run to analyze results
manually.
How to insert check point through Active Screen
Start Recording Help Menu Click on about Click on Bit Map Stop
Recording Click on Active Screen Icon Right click on Bit Map whichyou want to check Click on Insert Bitmap Check Point Click Ok Enter
7/30/2019 QTP Class Notes 1
15/82
option to insert statement (Before current Step / After Current Step) Click on
Ok Close current application (Flight 4a) Open another application (Flight
4b) Click run to analyze results manually.
3) Database Check Point
To automate backend testing we are using Database CheckPoint. During this testing we are validating backend table in termsof Data validation and data integrity.
Data validation means that the correctness of storing valuesinto backend table.
Data integrity means that the impact of stored values onexisting data table content. In this we will be concentrate on
primary keys, foreign keys, unique keys, . etc.,To automate backend testing we can follow below approach.
4
1
5
Actual Data
3
2
7/30/2019 QTP Class Notes 1
16/82
Expected Value
= = Fail= ! Pass
Step 1: Connect to Database using DSN (Data Source Name)Step 2: Execute Specified Select statement.Step 3: Retrieve the result of SQL StatementStep 4: Perform any db Operation.Step 5: Compare expected data with actual data to verify the impact of
frontend operation on backend table content.
Navigation
Insert Menu Check Point Database Check Point Select Specify SQLStatement Manually Next Create Machine Data source (Select Datasource) Select DSN (QT_FLIGHT32) Click Ok SQL Statement (Enteryour specified SQL Statement Ex:. select * from orders) Finish Change
the Check Point Name
Click Ok
Open Frontend (perform any dboperation like insert, delete, update) Click Run Analyze results manually.
To Create New DSN
*) First of all you create One database in MS Access with specified table.
Navigation
Insert Menu Check Point Click on Database Check Point Select
Specify SQL Statement Manually
Next
Create
Machine Data source(Select Data source) New Select type of data source (User [Single user] /System Data Source [multiple users]) Next Select a Driver (MicrosoftAccess Driver) Select database Click Ok Enter Data Source Name withdescription Click Ok Click Ok Take your specified statement (Table)Ex:. select * from orders) Finish Click Ok.
Note Database Check Point insertion is not possible through ActiveScreen.
4) Test Check Point
We can use this checkpoint to conduct test on text present on the
7/30/2019 QTP Class Notes 1
17/82
Navigation
Start Recording Insert Menu Check Point Click on Text Check Point
Select object with hand icon Click Ok Enter Name of the Check
Point Enter your expected Text in Constant Select Matching [(1) Match
Case (2) Ignore Spaces (3) Exact Match (4) Text Not displayed] Click on Ok
Stop Recording Click run to analyze results manually.
How to insert check point through Active Screen
Start Recording Activate Window Stop Recording Click on Active
Screen Icon Right click onobject, which object text you want to check Select insert Text Check Point Click Ok Enter Checkpoint Name
Expected text fill in constant Select Matching [(1) Match Case (2)Ignore Spaces (3) Exact Match (4)
Text Not displayed] Select InsertStatement (Before / After Current
step) Click Ok Click run toanalyze results manually.
Regular Expressions:
Whenever the object text is changing dynamically at run time, we can useregular expressions. Ex
Expected Srnagar1 John Smith Suresh
5) Test Area Check Point
We can use this Checkpoint to conduct test on Text present in the
specified screen area.
NavigationStart Recording Insert Menu Check Point Click on Text Area
Check Point Select the area specified to check Click Ok Enter
Name of the Check Point Enter your expected Text in Constant or
click on to give Regular expression Select type of Matching [(1) MatchCase (2) Ignore Spaces (3) Exact Match (4) Text Not displayed]
Click on OkStop RecordingClick run to analyze
resultsmanually.
Note: Text Area Checkpoint is not possible through Active Screen.
Regular Expression.[A-Z] [a-z] [0-9]*
[A-Z] [a-z] [ ] [A-Z] [a-z]*[A-Z] [a-z]*
7/30/2019 QTP Class Notes 1
18/82
We can use this Checkpoint to verify the properties of a web page.Navigation
Start Recording Insert Menu Check Point Select Standard Checkpoint Show Image / Link with Hand Icon Select Page Click Ok EnterName of the Checkpoint Select Property [give your expected value (Load
time, No. of Images, No of links)] Click Ok Stop Recording Click Run Analyze Results manually.
7) Table Checkpoint
We can use this checkpoint to verify the content of a Web Table.Navigation
Start Recording Insert Menu Check point Select Standard Checkpoint
Select Image with Hand IconClickSelect Web
TableClick OkEnter name of the Checkpoint Select Cell Enter
your expected data in constant
Click Ok
Stop Recording
Run
AnalyzeResults manually.
Note:
For Web Table
Browser(Browser Text Object Name).Page(Page Name).WebTable(TableName).Check CheckPoint(Check Point Name)
For Page Check Point
Browser(Browser Text Object Name).Page(Page Name).CheckCheckPoint(Check Point Name)
8) Image Check Point
To verify the properties of an Image, we can use ImageCheckpoint.
Browser(Browser Text Object Name).Page(Page Name).Image(Image
Name).Check CheckPoint(Check Point Name)
Navigation
Start Recording
Insert Menu
Check point
Select Standard Checkpoint Select Image with Hand Icon Click Click Ok Enter name of theCheckpoint Select Property (Alt) [give your expected value to that property] Click Ok Stop Recording Run Analyze Results manually.
How can we check Tool Tips Alt Property.
9) XML Check Point
To verify the content of an XML file we can use this check point.
NavigationInsert Menu Check point XML Check Point (From File) Browse your
7/30/2019 QTP Class Notes 1
19/82
manually.
0) Accessibility Check Point
We can use this checkpoint to verify whether the specified Web Page
meets W3C (WWWC) Standards or not (World Wide Web Consortium
Standards)
7/30/2019 QTP Class Notes 1
20/82
Navigation
Tools Menu Options Web Tab Advanced Select / Check in thecheck point [ActiveX Check, Alt Property Check, Applet Check, Frame Titles
Check, Multimedia Links check, Server-side Image Check, Tables Check] Ok Ok Start recording Insert Menu Check Point Click on
Accessibility Check Point Show Web Page with Hand Icon Click OkEnter Name of the CheckpointClick OkStopRecordingRunAnalyze Results manually.
Note
Page Checkpoint, Table Checkpoint, Image Checkpoint, Accessibility
Checkpoint, XML Checkpoint are applicable for Web Pages only.
OBJECT REPOSITORY
It is an interface between Tool and Application Build. Object Repository
consists of Recorded Objects description.
1 AUT
3
5
4
2
Automation Testing 19
7/30/2019 QTP Class Notes 1
21/82
(1)Start Recording
During Recording(2)Learn Object (Storing the object in Object Repository)(3)Script Generation(4)Catch Entry in Object Repository
During Run(Object Properties in Object Repository )(match the properties in AUT)
(5)Identify Object in AUT
AUT means Application Under Test.
To open Object Repository
Resources Menu Object Repository (or) Ctrl+RThere are (2)
Types of Objectssuch as (1) RunTime Object (2)Test
Object.
Run Time Object:
Test Object:
How to Add objects in Object Repository.
Navigation
Open Object Repository Click on Add Object Icon Show Object with
Hand Icon Click Ok Select Option [Select Object Only, Default Object
Types, All Object Types, Selected Object Types] Click Ok.
TYPES OF OBJECT REPOSITORY
1) Local Repository (Pre-Action Repository [Related to correspondingAction]
2) Shared Repository [Specific to multiple actions]How to create Shared Repository?
Open Object Repository File Menu Click Export Local Objects Enter
File Name Click Save (It will save as *.tsr)
What is the extension of the Shared Repository?
.tsr (Test Shared Repository)
Run Time Object is the object which is present in theAUT (Application under Test)
Test object is a reference of Run Time Objects which iscreated by QTP in Object Repository.
7/30/2019 QTP Class Notes 1
22/82
Resources Menu Associate Repository Click on Add Select /
Location of Repository file path Click Open Associate with Action Click Ok.
7/30/2019 QTP Class Notes 1
23/82
How to associate Repository file during Runtime
repositoriescollection.Add Repository file path Ex:
repositoriescollection.Add F:\loginrep.tsr
Note: In QTP every action will have one local repository, apart from that
localrepository one can associate more than one shared repository to
the action.
*.tsr
*.tsr
*.tsr
Module Test Script Module Test Repository
(*.mts) (*.mtr)Some people are calling it as mercury test script ,mercury test repositoryHow to edit Shared
Repository? Navigation
Resources Menu Object Repository Manager File Menu Open Select the Shared Repository File to be edit Open File Menu Enable
Editing then select which object to be edited Save.
Automation Testing 21
7/30/2019 QTP Class Notes 1
24/82
Object Repository Comparison Tool:
We can use this tool to compare two shared object repository files.Navigation:
Resources Menu Object Repository Manager Tools Menu Object
Repository Comparison Tool Select the (2) Shared Object Repository Files
you want to compare Ok Analyze statics.
Object Repository Merge Tool
We can use this tool to merge Two shared object Repository files.
Ex:
*.tsr *.tsr *.tsr
Insert UpdateInsert
+ = CancelCancel Cancel
ResetReset Reset Update
Navigation
Resources Menu Object Repository Manager Tools Menu ObjectRepository Merge Tool Select the (2) Shared Object Repository Files youwant to Merge Click Ok Save
Object Spy
We can use this option to know the properties and methods of specifiedobject.Navigation
Tools Menu Object Spy Click on Show your specified object with
ClickAnalyze properties and methods.
OBJECT IDENTIFYING:
Object Identification Mechanism is based on FOUR Types of propertiesand Ordinal Identifier.
Mandatory AssistiveProperties Properties Normal Identification Mechanism
Native Class: Enable: Matching MechanismText: Focused:
Base Filter Optional FilterProperties Properties
Smart Identification MechanismAbs-X: Window ID:
Filtering MechanismAbs-Y: X:Y:
7/30/2019 QTP Class Notes 1
25/82
Ordinal Identifier
Location
Index
Creation Time
QTP Will Follow below process to learn the object during Recording Time.
First of all QTP will learn all the mandatory properties and verify whetherthese properties are sufficient or not to identify the object uniquely. If it feelsthese properties are sufficient to identify the object uniquely, then it will stoplearning, otherwise it will learn first Assistive Property and verify whether these
properties are sufficient or not to identify the object uniquely. If it feels theseproperties are also not sufficient to identify object uniquely, then it will learn
2nd
Assistive Property and verify whether these properties are sufficient or notto identify object uniquely. If it feels these properties are also not sufficient to
identify object uniquely, then it will learn 3rd Assistive Property and verifywhether these properties are sufficient or not to identify the object uniquely, likethis the process continuous till the QTP satisfy to identify the object uniquely oruntil completion of all the properties learning present in the Assistive Propertylist.
After completion of all Assistive Properties learning present in theAssistive Property list, still QTP not satisfy to identify the object uniquely, thenfinally it will learn Ordinal Identifier and stop learning.
SMART IDENTIFICATIONIf you select Smart Identification QTP follows below process during
Recording.First of all it will learn all the Mandatory Properties along with Base
Filter Properties and Optional Filter Properties at a time. But MandatoryProperties will be stored in Object Repository, where Base Filter Propertiesand Optional Filter Properties will be stored in a secrete location. Apart fromthis the process of learning remains same as above.
QTP Will follow below process to identify the object during Run Time
First of all QTP will take all the properties present in the ObjectRepository except Ordinal Identifier and try to identify the object. If it fails toidentify the object, then it will forget / leave the Object Repository and take thealternative description (Base Filter Properties and Optional Filter Properties). Inthis first of all, it will take all the base filter properties and try to identify theobject. If it fails to identify the object then it will take first Optional filterProperty and try to identify the object. If it fails to identify the object then it will
take 2nd
Optional Filter Property and try to identify the object. If it fails
Automation Testing 23
7/30/2019 QTP Class Notes 1
26/82
to identify the object with that property also, then it will take 3rd
Optional Filter
Property and try to identify the object, like this the process continue till the QTPidentify the object uniquely or until completion of all the properties present inthe optional filter properties list.
After completion of all the properties present in the Optional Filter
Properties list still QTP not able to identify the object uniquely, then it willcome back to Object Repository and search for Ordinal Identifier, if it isavailable, using that QTP roughly identify the object.
ORDINAL IDENTIFIER
(a) Location
If you select Location as Ordinal Identifier, then QTP generates sequenceof numbers like 0, 1, 2, 3 . based on the location (Place) of the objectin a screen.
(b)Index
If you select Index as Ordinal Identifier then QTP generates sequence ofnumbers like 0, 1, 2, 3 based on the sequence of the programs of theobject.
(c) Creation Time (For Browsers only)
If you select Creation Time as Ordinal Identifier then QTP generatessequence of numbers like 0, 1, 2, 3 based on loading of a page in
browser time.Navigation
Tools Menu Object Identification Select (Standard Window) as
Environment Select Test Object Class which you want to configure Takerequired mandatory properties / Assistive Properties by clicking Add / Remove
Button Select Enable Smart Identification Properties Click Configure Take Base Filter / Optional filter Properties by clicking Add / Remove Button
Click OkSelect Ordinal IdentifierClick OkStartRecordingRecord required Operation Stop Recording Run Analyze Results manually.
Virtual Objects
It is used to recognize specified screen area as standard object.
Navigation
Tools Menu Virtual Objects New Virtual Object Next Select
Standard Class under Select Combo Box click Next Mark object Select
the Object Next Next Finish.
Drawbacks of Object Repository
It takes lot of time for identifying the object, when the object is changing
dynamically during Run time.
7/30/2019 QTP Class Notes 1
27/82
DESCRIPTIVE PROGRAMMING (VB SCRIPTING)
If we specify the description of the object in the program it self that can
be called as Descriptive Programming.
Using Descriptive Programming we can execute test script withoutobjects in Object Repository / we can execute the test script without ObjectRepository.
Advantages of Descriptive Programming
i) Fast execution.ii) Easy to identify the objects, when the objects are dynamic in nature.iii)We can prepare Script without having build.
Disadvantages of Descriptive Programming
i) It takes lot of time to design test design (Time consuming for test script
design)
To design Descriptive Programming, there are (2) ways such as (1)
Specifying the properties and its values directly in the statement (script) (2)
Description Object.
Syntax / Code
window(P1:=Value, P2=Value, .).Object(P1:=Value, P2=Value,.).Operation / Method.
Ex(1):
Prepare descriptive Programming for Login Operation in Flight
Reservation
Dialog(""text:=Login", width:=320").Activate Dialog("text:=Login",
width:=320).WinEdit("attached text:=Agent Name:"). Set "suresh"
Dialog(""text:=Login", width:=320").WinEdit("attached text:=Password:").
SetSecure "4941cfd5b7a0bf66f6e9ded8bacb20164598f9ec"Dialog(""text:=Login", width:=320").WinButton("text:=OK").Click
(2) Description Object.
To create Description Object we can follow below syntax.
Syntax / Code
Set Object Name = Description.CreateObject Name (Property Name).Value = Property Value
Automation Testing 25
7/30/2019 QTP Class Notes 1
28/82
Ex(2):
Prepare descriptive Programming for Login Operation in Flight
Reservation
Set dia = description.Create
dia ("text").value="Login"
dia ("width").value = 320
Set uid = description.Create uid ("attached
text").value="Agent Name:"
Set pwd = description.Create pwd
("attached text").value="Password:"
Set but = description.Create
but ("text").value = "OK"
Dialog(dia).Activate
Dialog(dia).WinEdit(uid).Set "suresh"Dialog(dia).WinEdit(pwd).SetSecure "4941d5a45019d0ff89dabd026735808c9030b1f0"Dialog(dia).WinButton(but).Click
Ex(3):
Prepare descriptive Programming for Open a Record in Flight Reservation
Set win = description.Create win
("text").value="Flight Reservation"
Set menuobj = description.Create
menuobj ("menuobjtype").value=2
Set dia = description.Create dia
("text").value="Open Order"
Set cbox = description.Create cbox
("text").value = "&Order No."
Set editobj = description.Create
editobj ("window id").value = 1016
Set but = description.Create
but ("text").value = "OK"
26 Automation Testing
7/30/2019 QTP Class Notes 1
29/82
Window(win).Activate
Window(win).WinMenu(menuobj).Select "File;Open Order..."Window(win).Dialog(dia).WinCheckBox(cbox).Set "ON"Window(win).Dialog(dia).WinEdit(editobj).Set "15"Window(win).Dialog(dia).WinButton(but).Click
VB Script Statements
(1) Left
We can use this function to get a specified number of charactersfrom the left side of a string.
Syntax: left (String, number)Ex:x="sairam"msgbox left(x,3)
(2) RightWe can use this function to get a specified number of characters from the
right side of a string. Syntax: right(String, number)Ex: x="sairam"msgbox right(x,3)
(3) Len
We can use this function to find length of a stringSyntax: len (String)Ex:
x="sairam" msgboxlen(x)
(4) Mid
We can use this function to get a specified number of characters from thegiven string.Syntax: mid (String, Start Position, length)
Ex: x="$1245" msgbox
mid(x,2,len(x)-1)
Ex: x="Rs.14258/-"
msgbox mid(x,4,len(x)-5)
5) LTrim
We can use this function to remove spaces from the left side of a string.
Syntax: ltrim (String)
Ex: x=" Sai"msgbox ltrim(x)
7/30/2019 QTP Class Notes 1
30/82
6) RTrim
We can use this function to remove spaces from the right side of a string.Syntax: rtrim (String)
Ex: x="Sai "
msgbox rtrim(x)
7) Trim
We can use this function to remove spaces from both the sides of a string.Syntax: trim (String)
Ex: x=" Sai "
msgbox trim(x)
8) UCaseWe can use this function to convert Lower Case into Upper Case
Syntax: ucase (String)
Ex: x="sairam"
msgbox ucase(x)
9) LCase
We can use this function to convert Upper Case into Lower Case
Syntax: lcase (String)
Ex: x="SAIRAM"
msgbox lcase(x)
10) Strreverse
We can use this function to reverse the string.Syntax: strreverse (String)
Ex: x="SAIRAM"
msgbox strreverse(x)
(11) Strcomp
We can use this function to compare two stringsSyntax: strcomp (String1, String2, Compare)
0 1Binary Comparison Textual Comparison
Ex:
x="SAIRAM"
7/30/2019 QTP Class Notes 1
31/82
If strcomp(x,y,0)=0 thenmsgbox "Both are Equal"elsemsgbox "Both are not Equal"
end if
(12) Cint
We can use this function to convert given value into Integer.Syntax: cint (expression)
Ex: x="10.54"
msgbox cint(x)
(13) Cdbl
We can use this function to convert the given value into double.
Syntax: cdbl (expression)
(14) Cstr
We can use this function to convert given value into String.Syntax: cstr (expression)
(15) Round
We can use this function to rounding the value.Syntax: round (expression, No. of decimal places)
Ex: x="10.123456789"
msgbox round(x,3)
16) Split
It is used to return 0 Zero Based one dimensional array containing aspecified no. of substrings.Syntax:
Split (expression, delimiter)Ex:s="India is a great country"
arr=split(s, " ")msgbox arr(0) Indiamsgbox arr(1) ismsgbox arr(2) amsgbox arr(3) great
msgbox arr(4) country
7/30/2019 QTP Class Notes 1
32/82
It is used to return a string created by joining a specified no. of substrings
contained in an array.
Syntax:
join (list, delimiter)Ex:s="India is a great country"arr=split(s, " ")
msgbox arr(0) Indiamsgbox arr(1) ismsgbox arr(2) amsgbox arr(3) greatmsgbox arr(4) country
msgbox join(arr, " ")
NoteHow to add two variables values.a="Sai"
b="Ram" msgbox
a&space(10)&b
18) Space
It is used to create a specific No of spaces
Syntax:space (Number)
(19) Rem
It is used to insert comment.Syntax remstatement
Note
Ctrl + M Comment BlockCtrl +Shift + M Uncomment Block
(20) Date
It is used to return current system date.Syntax:
msgbox date
(21) TimeIt is used to return current system time.
S
7/30/2019 QTP Class Notes 1
33/82
(22) Now
Syntax
msgbox now
(23) WeekdaynameSyntax
msgbox weekdayname(weekday(date))
Note
The default variable type in VB Script is Variant
For Loop
Syntax
For i=1 to n step1..................................................statement..................................................
Next
While Loop
SyntaxWhile condition
.........................statement.........................
Wend
If Condition
Syntax Ex:
If condition Then a=10statement b=20else If a>b Thenstatement msgbox "a is greater"
End If elsemsgbox "b is greater"
End If
Else If
Syntax Ex:If condition Then a=10statement b=20
7/30/2019 QTP Class Notes 1
34/82
statementelsestatementend if If a>b and a>c Then
End If msgbox "a is greater"else if b>c thenmsgbox "b is greater"elsemsgbox "c is greater"End If
End If
Select Case
It is similar to Switch StatementSyntax Ex:
Select Case Variable x=inputbox("Enter alphabet")Case "value1", "value2", Select Case x
Statement Case "a", "e", "i", "o", "u"Case Value msgbox "It is Vowel"
Statement Case elseCase else msgbox "It is not Vowel"
Statement End SelectEnd Select
How to declare variables in VB Script?
To declare variables in VB Script we are using one script.
(i) Option Explicit
To forcibly declare variables (This statement display error message for
undeclared variables)
(ii)Dim Variable1, Variable2, Variable3, .. Variables
(To declare variables)
METHODS
GetVisibleText
We can use this method to capture visible text.Code:
Variable=Window("Window Name").Object("Object Name").GetVisibleText()
Ex:
7/30/2019 QTP Class Notes 1
35/82
x = Dialog("Login").WinEdit("Agent Name:").GetVisibleText()
msgbox x
Output
GetROProperty
We can use this method to capture run time property value intovariables. OrWe can use this method to capture object property from the application
Code
Variable = Window("Window Name").Object("Object Name").GetROProperty
("Property Name")
Ex:
Dialog("Login").Activate
x = Dialog("Login").WinButton("OK").GetROProperty("Enabled")
msgbox x
Output
GetTOProperty
We can use this method to capture text object value into variable.
OrWe can use this method to capture object property value from the object
R it
7/30/2019 QTP Class Notes 1
36/82
Variable = Window("Window Name").Object("Object Name").GetTOProperty("Property Name")Ex:
Dialog("Login").Activate
x = Dialog("Login").WinButton("OK").GetTOProperty("Enabled")
msgbox x
Output
Report Event:
We can use this method to report an event to the Test Result Window.Syntax:
reporter.ReportEvent EventStatus, ReportStepName, Details
micPass (0)
micFail (1)
micDone (2)
micWarning (3)
It is used to display your specified message in Quick Test Print log.Syntax:
Print Message
Ex:a=10
b=20If b=a+10 Then
msgbox "b is equal to a"print "b is equal to a"reporter.ReportEvent micPass, "b is equal to a", "Test is Pass"elsemsgbox "b is not eqaul to a"
print "b is not equal to a"reporter.ReportEvent micFail, "b is not equal to a", "Test is fail"
d f
7/30/2019 QTP Class Notes 1
37/82
Step Generator (F7)
It is used to generate steps in the Test pane without click on startRecording.
Step Generator consists of statements in three categories such as(i) Functions(ii) Utility objects(iii) Test Objects.
(i) Functions
This category specifies all general and mathematical operationssuch as left, right, len, time, cint, cdbl, cstr, ltrim, rtrim, trim etc.,
(ii) Test Object
This category specifies the operations which are performed on theobjects such as Set, Select, Activate, SetSecure, Click, GetVisibleText,GetROProperty, GetTOProperty, GetItem, GetItemCount, GetContent .Etc.,
iii) Utility Objects
This category specifies all miscellaneous operations such as
DataTableOperations, SystemUtil Operations, QCUtil Operations,
Recovery Operations etc.,
Ex
Prepare script for calculation Test in Application Flight Reservation
Option explicitDim x,y,tot,iFor i = 1 to 5 step 1 Window("FlightReservation").ActivateWindow("Flight Reservation").WinMenu("Menu").Select "File;Open Order..."Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order
No.").Set "ON"Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set i
Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Clickx = Window("Flight Reservation").WinEdit("Tickets:").GetVisibleText()y = Window("Flight Reservation").WinEdit("Price:").GetVisibleText()y=mid(y,2, len(y)-1)tot = Window("Flight Reservation").WinEdit("Total:").GetVisibleText()tot=mid(tot,2, len(tot)-1)If cdbl(tot)=cdbl(x) * cdbl(y) Then
reporter.ReportEvent micPass, "Calculation is correct", "Test is Pass"else
reporter.ReportEvent micFail, "Calculation is not correct", "Test is fail"End If
7/30/2019 QTP Class Notes 1
38/82
Expected Activate
Window
Enter User Name and PasswordClick Ok
If Next is enabled, User is authorized. Ifnext is disabled, User is unauthorized.
Prepare Test Script for above expected.
Option Explicit
Dim x
Dialog(Login).Activate
Dialog(Login).WinEdit(User Name).Set sureshDialog(Login).WinEdit(User Name).SetSecure xxxxxx
Dialog(Login).WinButton(Ok).ClickX= Dialog(Login).WinButton(Next).GetROProperty("Enabled")If x = True Then
reporter.ReportEvent micPass, "Next is Disabled", "Test is Pass"else
reporter.ReportEvent micFail, "Next is Enabled", "Test is fail"End If
(I have prepared the same in VB and tested on the same)Option explicit
Dim x, y
VbWindow("frmLogin1").VbEdit("txtUserName").Set "suresh"
VbWindow("frmLogin1").VbEdit("txtPassword").SetSecure
"49422cd7dcd270949c6d92cc9fbcc1fcb1d0795d6e15"
x = VbWindow("frmLogin1").VbButton("Next").GetROProperty("Enabled") If
x = "False" Then
reporter.ReportEvent micPass, "Next is Disabled", "Test is Pass"elsereporter.ReportEvent micFail, "Next is Enabled", "Test is fail"
End If
VbWindow("frmLogin1").VbButton("OK").Clicky = VbWindow("frmLogin1").VbButton("Next").GetROProperty("Enabled")
If y = "True" Then
reporter.ReportEvent micPass, "Next is Enabled", "Test is Pass"else
reporter.ReportEvent micFail, "Next is Disabled", "Test is fail"End If
Automation Testing 37
7/30/2019 QTP Class Notes 1
39/82
Ex:
Expected ActivateWindow Enter Name asSuresh Click DisplayCheck Output
Display the results in Quick Test Print Log
Script
Option explicitDim x, MyarrayVbWindow("Sample").VbEdit("Test1").Set "Suresh"VbWindow("Sample").VbButton("Display").Clickx = VbWindow("Sample").VbEdit("Output").GetVisibleText()
Myarray = split(x, " ")If Myarray (3) = "Suresh" Then
print "Test is Pass"else
print "Test is fail"End If
Output
Data Driven Testing
The repetition of the same test for more than one time with multiple testdata is called Data Driven Testing. It is also known as Re-testing or iterationtestingTesting. There are different ways.
1) Dynamic Test Data Submission (Key Board)
2) Through Data Table (Excel Sheet / Data Base)3) Through Flat File (Notepad)
1) Dynamic Test Data Submission
Some times we are conducting data driven test depending on
multiple test data through Key Board.
.. AUT
Key Board Test Script (Application
.. Under Test)
7/30/2019 QTP Class Notes 1
40/82
Ex
If you open record in Flight Reservation Application, Update Button is
Disabled
Option explicitDim i, x, y For i=1to 3 Step 1y=inputbox ("Enter Order No.") With
Window("Flight Reservation")
.WinMenu("Menu").Select "File;Open Order..."
.Dialog("Open Order").WinCheckBox("Order No.").Set "ON"
.Dialog("Open Order").WinEdit("Edit").Set y
.Dialog("Open Order").WinButton("OK").ClickEnd withx = Window("Flight Reservation").WinButton("Update Order").GetROProperty
("Enabled")If x="False" Then
reporter.ReportEvent micPass, "Update is disabled", "Test is Pass"else
reporter.ReportEvent micFail, "Update is enabled", "Test is fail"
End If
Next
Ex: Expected1) Input 1 & Input 2 Values2) Click OK3) Check Results4) Display Results in Quick Test Print ID5) 10 Times
Script
Option explicit Dimi, x, y, z For i=1 to10 step 1x=inputbox ("Enter Input1") y=inputbox ("Enter
Input2")
VbWindow("Multiply").VbEdit("Input1").Set x
VbWindow("Multiply").VbEdit("Input2").Set y
VbWindow("Multiply").VbButton("OK").Click
z = VbWindow("Multiply").VbEdit("Result").GetVisibleText() If
cint(z) = cint(x) * cint (y) Then
print "Test is pass"
else
Automation Testing 39
7/30/2019 QTP Class Notes 1
41/82
print "Test is fail"
End If
Next
2) Through Data Table
Some times we are conducting Data Driven Test depending on multiple Testdata through data Table. They are (2) ways such as
(i) Tester Test Own Data(ii)Import Data from database or other files.
i) Tester Test Own Data
Test Script
AUT
Script
With Window("Flight Reservation").WinMenu("Menu").Select "File;Open Order...".Dialog("Open Order").WinCheckBox("Order No.").Set "ON".Dialog("Open Order").WinEdit("Edit").Set datatable("test_data",dtGlobalSheet)
.Dialog("Open Order").WinButton("OK").ClickEnd with
7/30/2019 QTP Class Notes 1
42/82
x = Window("Flight Reservation").WinButton("Update Order").GetROProperty
("Enabled")
If x="False" Then print"Update is disabled" else
print "Test is fail"End If
Navigation
(1)
Start recording Record required operation (Open Record) Enhance testscript like as shown in above program Open data table Double Click onData table Column Name Enter Column Name Click Ok Enter value in
the data table Tools menu Click on Data Driver Select value whichyou want to parameterize Click Parameterize Select option [(i) Step bystep parameterization (ii) Parameterize all] Click Next Click on ParameterOption Select Data table column Name click Ok Click Finish ClickOk Click Run Analyze results manually.(2)
Record required operation Enhance Test Script like as shown in the aboveprogram Open Data Table Double Click on Data table Column Name enter Column Name click Ok Enter values in Data Table Replace input
values in the script with below statement.Data table (Parameter Name, dtGlobalSheet /
dtLocalSheet) (Data table column NameOr
Data table (parameter Id, Sheet ID)
(ii) Import Data from database or other files. (Before execution)
Design Time
Data table2
Run the
script
7/30/2019 QTP Class Notes 1
43/82
Navigation
Record required Operation Open Data table Right Click on Data table
SheetImportFrom dbSelect specific SQL Statement
ManuallySelect Maximum number of rows if required Next Click on
Create to Select DSN Machine data Source Select DSN Ok In SQL
Statement (Your specific statement Ex.: select * from Orders) Finish ReplaceInput value in the script with below statement Run Analyze Results manually.
Datatable(Parameter ID, Sheet ID)
Difference between Design Time Data Table & Run Time Data Table
Design time Data Table Run Time Data Table
1) It is viewed in the QTP Main 1) It is viewed in the QTP TestTest. Results.
2) It is created prior to the test 2) It is created in Test Results afterexecution. test execution.
3) It represents data from external 3) It represents a live version ofsources. design Time Data table.
Data Table Methods
(1)Add Sheet:We can use this method to add one new sheet to the run time
data table.
Syntax:Ex:
(2)Delete Sheet:
We can use this method to delete one specified sheet from theRun Time Data table.Syntax: datatable.DeleteSheet (Sheet_ID)
Ex: datatable.DeleteSheet (3)
(3)GetSheetCount
We can use this method to count number of sheets in the run timedata table.Syntax:
Ex:
42 A t ti T ti
datatable.GetSheetCountmsgbox datatable.GetSheetCount
datatable.AddSheet (Sheet_Name)datatable.AddSheet (input)
7/30/2019 QTP Class Notes 1
44/82
(4) GetRowCount
We can use this method to count number of rows in the 1st
sheet
(longest column) of the Run time data table.
Output
Syntax: datatable.GetRowCount
Ex: msgbox datatable.GetRowCount
(5) GetSheet
We can use this method to return a specified sheet from the RunTime data table.
Syntax: datatable.GetSheet(SheetID)Ex: msgbox datatable. GetSheet(1).GetRowCount
(6) Value
We can use this method to set or get value of cell in the specifiedparameter and the current row of the Rum time data table.
To set data
Syntax: datatable.Value(Parameter_Name, Sheet_Name) = Value / variableOr
datatable(Parameter_Name, Sheet_Name) = Value / variable
To get data
Syntax: Variable = datatable.Value(Parameter_Name, Sheet_Name)Or
Variable = datatable(Parameter_Name, Sheet_Name)
Ex:
Option explicit
Dim a, b, c
a=datatable.Value (1,1)
b=datatable.Value (2,1)
c=cint(a)+cint(b)
datatable.Value (3,1) = c
Note: Default property of Datatable is value
Automation Testing 43
7/30/2019 QTP Class Notes 1
45/82
(7) SetCurrentRow
We can use this method to take a specified row as current row in
the Run Time Datatable (By default it is 1st
Row of 1st
Sheet)
Syntax: datatable.SetCurrentRow(Row_Number)
Ex:
s="sairam"
datatable.SetCurrentRow (3)datatable.Value (1,1) = s(8) SetNextRow
We can use this method to take the row after the current Row asNew Current Row in the Run time data table.
Syntax: datatable.SetNextRowEx:
s="sairam"
datatable.SetCurrentRow (3)datatable.SetNextRowdatatable.Value (1,1) = s
(9) SetPrevRow
We can use this method to take the row before the current Row asNew Current Row in the Run time data table.
Syntax: datatable.SetPrevRowEx:
s="sairam"datatable.SetCurrentRow (3)datatable.SetPrevRowdatatable.Value (1,1) = s
(10) Import
We can use this method to import Microsoft Excel File to theRuntime Data Table (Including all sheets)
Syntax: datatable.Import Path of File
Ex: datatable.ImportF:\Inputdata.xls
a. ImportSheet
We can use this method to import a specified sheet of MicrosoftExcel Sheet to the Runtime Data table.Syntax: datatable.ImportSheet Path of File, Source Sheet,
DestinationSheet
Ex: datatable.ImportSheetF:\Inputdata.xls,3,1
7/30/2019 QTP Class Notes 1
46/82
(11) Export
We can use this method to export a copy of Run Time Data table toanother location (Including all sheets)
Syntax: datatable.Export Path of FileEx: datatable.Export
F:\Outputdata.xls
a. ExportSheet
We can use this method to export a copy specified sheet of Run
Time Data table to the existing or new Excel File. Syntax:datatable.ExportSheet Path of File, Sheet Name / Source SheetEx: datatable.ExportSheetF:\Outputdata.xls, 2
Ex: Prepare script for Update operation in Flight Reservation Application
by taking data from Excel file during Runtime.
Option explicit
Dim rowcount, i, ordnum, strname,x,y datatable.AddSheet ("data")datatable.ImportSheet "C:\Documents and Settings\SaiSarvani\Desktop\QTP\sample.xls", 1, "data"
rowcount = datatable.GetSheet ("data").GetRowCount WithWindow("Flight Reservation").Dialog("Open Order")
For i=1 to rowcount step 1
datatable.SetCurrentRow (i)
ordnum=datatable.Value (1, "data")
strname = datatable.Value (2, "data")
Window("Flight Reservation").WinMenu("Menu").Select "File;Open Order...".WinCheckBox("Order No.").Set "ON".WinEdit("Edit").Set ordnum
.WinButton("OK").ClickWindow("Flight Reservation").WinEdit("Name:").Set strnameWindow("Flight Reservation").WinButton("Update Order").Clickwait (10)
x = Window("Flight Reservation").ActiveX("Threed Panel Control").GetVisibleText()y="Update Done..."
If strcomp(x,y,1) = 0 Then
Automation Testing 45
7/30/2019 QTP Class Notes 1
47/82
reporter.ReportEvent micPass,"Update done", "Test is pass"else
End If
reporter.ReportEvent micFail, "Update fail", "Test is fail"
NextEnd With
Database Connection:
(i) Connection
We can use this class to establish a connection to the specified
database during RuntimeSyntax:Set ConnectionObject = CreateObject (ADODB.Connection)
conobj.open Provider=Provider Name
Ex:
MS Access
conobj.open Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Path of Database
SQL Server
conobj.open Provider=sqloledb.1; Server=IP Address; uid=Username; pwd=xxx;
database=Path of database
Oracle
conobj.open Provider=oraoledb.1; Server=xxx; userID=Username(scott);password=xxx(tiger)
Note:
To get provider Name
Open Notepad Save empty file with .udl Open that udl File ProviderTab Select Provider Next Select Database Test Connection Click
Ok Click Ok Open the same file in Notepad
(ii) Command
We can use this class to execute specified DML Statements (Insert,Update, Delete) on connected database.
Code:
Set comobj=createObject (ADODB.Command)
Comobj.ActiveConnection = conobjComobj.CommandText = SQL Statement
7/30/2019 QTP Class Notes 1
48/82
(iii) Recordset
We can use this class to execute specified select statement on
Code: connected database and retrieve the results.
Set rsobj = createObject (ADODB.recordset)Rsobj.open SQL Statement, conobj
Ex
Option explicitDim comobj, conobjSet conobj=createobject("ADODB.Connection")conobj.open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documentsand Settings\Sai Sarvani\Desktop\sample.mdb" Set
comobj=createobject ("ADODB.Command")
comobj.activeconnection = conobj
comobj.commandtext = "Insert into emp values ('Appa Rao', 101, 10000)"comobj.executeconobj.closeSet comobj = nothingSet conobj = nothing
(iv) Nothing
Noting is a keyword in VB Script, which is used to disassociate anobject variable from the actual object.
CodeSet objectname = nothing
Ex:
How to set multiple records into database table by taking the data from
Excel file
7/30/2019 QTP Class Notes 1
49/82
Set conobj=createobject("ADODB.Connection")conobj.open "PRovider=Microsoft.jet.oledb.4.0;data Source = C:\Documents and Settings\Sai Sarvani\Desktop\sample.mdb"Set comobj=createobject("ADODB.Command")comobj.activeconnection=conobjdatatable.AddSheet ("data")datatable.ImportSheet "C:\Documents and Settings\Sai Sarvani\Desktop\testdata.xls",1,"data"
47
rcount=datatable.GetSheet("data").getrowcount
For i=1 to rcount step 1
datatable.SetCurrentRow (i)ename=datatable.Value (1, "data")
eno=datatable.Value (2, "data")esal=datatable.Value (3, "data")
comobj.commandtext = "insert into emp values ('"&ename&"', "&eno&","&esal&")"
comobj.executeNextconobj.closeSet conobj = nothing
Set comobj=nothing
Ex:
How to get data from database table?
Option explicit Dim
conobj,rsobj,username,password Set
conobj=createobject("ADODB.connection")
conobj.open "PRovider=Microsoft.jet.oledb.4.0;
data Source = C:\Documents and Settings\Sai Sarvani\Desktop\sample.mdb"Set rsobj=Createobject("ADODB.recordset")
rsobj.open "select * from login", conobjrsobj.movefirstWhile not rsobj.eof
username=rsobj("uid")password=rsobj("pwd")
SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTestProfessional\samples\flight\app\flight4a.exe" Dialog("Login").WinEdit("Agent
Name:").Set usernameDialog("Login").WinEdit("Password:").SetSecure crypt.Encrypt (password)
Dialog("Login").WinButton("OK").Click
7/30/2019 QTP Class Notes 1
50/82
reporter.ReportEvent micPass, "Login success", "Test is Pass"Window("Flight Reservation").WinMenu("Menu").Select "File;Exit"
elsereporter.ReportEvent micFail, "Login Fail", "Test is fail"
Dialog("Login").Dialog("Flight Reservations").WinButton("OK").ClickDialog("Login").WinButton("Cancel").ClickEnd Ifrsobj.movenextWend
rsobj.close
conobj.close
Set rsobj=nothing
Set conobj=nothing
Ex:Database Testing
Option explicit
Dim con, con1, rs, rs1, DOF, FF, FT, PN, NOTC,TOF,x
Set con=createobject("ADODB.connection") con.open
"DSN=QT_Flight32"
Set rs=createobject("ADODB.recordset") Set
con1=createobject("ADODB.connection")
con1.open "Provider=microsoft.jet.oledb.4.0; data source=C:\Documents andSettings\Sai Sarvani\Desktop\sample.mdb" Setrs1=createobject("ADODB.recordset")rs1.open "select * from data",con1rs1.movefirstWhile not rs1.eof
DOF=rs1("dof")
FF=rs1("flyfrom")
FT=rs1("flyto")
PN=rs1("pname")
NOTC=rs1("not")
TOF=rs1("tof")
Window("Flight Reservation").WinMenu("Menu").Select "File;New Order"Window("Flight Reservation").ActiveX("MaskEdBox").Type DOFWindow("Flight Reservation").WinComboBox("Fly From:").Select FFWindow("Flight Reservation").WinComboBox("Fly To:").Select FTWindow("Flight Reservation").WinButton("FLIGHT").Click Window("FlightReservation").Dialog("Flights Table").WinList("From").Select TOF
Window("Flight Reservation").Dialog("Flights Table").WinButton("OK").ClickWindow("Flight Reservation").WinEdit("Name:").Set PN Window("Flight
7/30/2019 QTP Class Notes 1
51/82
Reservation").WinButton("Insert Order").Clickwait(10)x = Window("Flight Reservation").WinEdit("Order No:").GetVisibleText()rs.open"select * from orders where Order_Number="&x,con
If rs("Customer_Name")=PN and trim(rs("Tickets_Ordered"))=trim(NOTC)Then
reporter.ReportEvent micPass, "Data inserted", "Test is passed"
else
reporter.ReportEvent micFail, "Data is not incered", "Test is fail"End Ifrs1.movenextrs.close wend
rs1.closecon1.closecon.close
Set rs1=nothingSet rs=nothingSet con1=nothingSet con=nothing
) Through Flat FileSome times we are conducting data driven testing depending on multiple
test data from Text files.To manipulate flat file content for testing we can prepare script like as
below.Set fso = createobject(Scrpiting.filesystemobject)Set f=fso.opentextfile (Path of text file, mode[Read-1, Write-2,Append-8])while f.atendoflile = false
s=f.readline..... .set sWend
f.close
Ex
Option explicit
7/30/2019 QTP Class Notes 1
52/82
Set fso=createobject("Scripting.filesystemobject")Set f=fso.opentextfile ("C:\Documents and Settings\Sai Sarvani\Desktop\input.txt",1)f.skiplineWith Window("Flight Reservation").Dialog("Open Order")
While f.atendofline = false
s=f.readline
Window("Flight Reservation").WinMenu("Menu").Select "File;Open Order...".WinCheckBox("Order No.").Set "ON".WinEdit("Edit").Set s.WinButton("OK").Click
x = Window("Flight Reservation").WinButton("Update Order").GetROProperty("Enabled")If x="False" Then
reporter.ReportEvent micPass, "Update is disabled", "Test is Pass"elsereporter.ReportEvent micFail, "Update is enabled", "Test is fail"End If
Wend
End With
f.close
GetItemsCount
We can use this method to count number of items in the combo box.Code
Variable = Window("Window Name").WinComboBox("Combo Box Name").GetItemsCount()
Ex:
s = Window("Flight Reservation").WinComboBox("Fly From:").GetItemsCount()
msgbox s
GetItemWe can use this method to get a specified item from the Combo Box
Code
variable = Window("Window Name").WinComboBox("Combo Box Name").
GetItem(Item Number)
Ex:
s = Window("Flight Reservation").WinComboBox("Fly From:").GetItem(4)
msgbox s
GetContent
W hi h d f h C b B
7/30/2019 QTP Class Notes 1
53/82
variable = Window("Window Name").WinComboBox("Combo Box Name").
GetContent()
Ex
s = Window("Flight Reservation").WinComboBox("Fly From:").GetContent()
msgbox s
Ex:
How to count number of items in the Fly From Combo Box and how to
display their name one by one.
s = Window("Flight Reservation").WinComboBox("Fly From:").GetItemsCount()msgbox sFor i=0 to n-1 step 1
y = Window("Flight Reservation").WinComboBox("Fly From:").GetItem(i)msgbox y
Next
How to display FlyFrom Combo Box items one by one into Notepad
Option explicitDim fso,s,x,nSet fso=createobject("Scripting.filesystemobject")Set s=fso.opentextfile ("C:\Documents and Settings\Sai Sarvani\Desktop\
sample.txt",2)x = Window("Flight Reservation").WinComboBox("Fly From:").GetItemsCount()For i=0 to n-1 step 1n = Window("Flight Reservation").WinComboBox("Fly From:").GetItem(i)s.writeline nnext
s.close
How to display Flyfrom Combo box items one by one into Runtime Datatable and the same data table export to Excel Sheet datatable.AddSheet("output").Addparameter "From", " "n = Window("Flight Reservation").WinComboBox("Fly From:").GetItemsCount()
For i=0 to n-1 step 1x = Window("Flight Reservation").WinComboBox("Fly From:").GetItem(i)
datatable.SetCurrentRow (i+1)
datatable.Value ("From", "output") =x
Next
datatable.ExportSheet "C:\Documents and Settings\Sai Sarvani\Desktop\
output1.xls", "output"
7/30/2019 QTP Class Notes 1
54/82
If you select one item from Fly From Combo Box, that item should be
disappeared in Fly To Combo Box
n = Window("Flight Reservation").WinComboBox("Fly From:").GetItemsCount()
For i=0 to n-1 step 1x = Window("Flight Reservation").WinComboBox("Fly From:").GetItem(i)
Window("Flight Reservation").WinComboBox("Fly From:").Select xm = Window("Flight Reservation").WinComboBox("Fly To:").GetItemsCount()
For j=0 to m-1 step 1y = Window("Flight Reservation").WinComboBox("Fly To:").GetItem(j)If strcomp(x,y,0)0 Then
reporter.ReportEvent micPass,"Items are not same", "test is Pass"else
reporter.ReportEvent micFail,"Items are same", "Test is fail"End If
Next
Next
How to count number of subfolders and files in a specified folder and how
to display their names one by one? Prepare script for above expected?
Option explicit Dimfso,f,sf,n,g,ft,m,kSet fso=createobject("Scripting.filesystemobject")
Set f=fso.folder ("F:\XP")
Set sf=f.subfolders
n=sf.count msgboxn
For each g in sf
msgbox g.nameNextSet ft=f.filesm=ft.countmsgbox m
For each k inft
msgbox k.nameNext
Synchronization Point
The time map between tool and application build. To give waiting time tothe tool there are (3) ways such as
(i) Synchronization Point(ii) Wait(iii) Increase timeout
7/30/2019 QTP Class Notes 1
55/82
We can use this option to give waiting time to the tool based onspecific object property value.
Code
Window("Window Name").Object("Object Name").WaitProperty "PropertyName", Property Value, Timeout in Milliseconds.Navigation
Place the cursor in your required place of test script Click on Start recording
Insert MenuSynchronization PointShow object with Hand
IconClick click Ok Select property Name (Enable) Enter Property
Value (True) Set timeout in Milliseconds Click Ok Stop Recording.Note
1 Second = 1000 Milliseconds
(ii) Wait
We can use this statement to give fixed waiting time to the tool.Code
Wait (Time in seconds)
Ex: wait (10)
iii) Increase timeout
QTP maintain 20 Seconds as default object synchronization Time out.That time out is not sufficient, then we will increase Timeout in settings.
Navigation
File Menu Settings Run Tab Change Object Synchronization time outclick Ok.
Start Transaction & End Transaction
It is used to calculate the time taken to execute a block of statements or toestimate the speed of processing.Syntax
Services.StartTransaction .
Statements..Services.EndTransaction
54 Automation Testing
7/30/2019 QTP Class Notes 1
56/82
Navigation
Place the cursor in the required position Insert Menu Start Transaction Enter Transaction Name Click Ok place the cursor at end position (or)where you want to stop transaction Insert Menu End Transaction Click
Ok click run Analyze results manually.
With
We can use this statement to decrease the length of the program.Navigation
Record required Operation Edit Menu Advanced Apply with to script(or) Ctrl + W (To remove with statement Ctrl + Shift + W)Ex:Window("Flight Reservation").WinMenu("Menu").Select "File;Open Order..."
With Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON".WinEdit("Edit").Set s.WinButton("OK").Click
End with
Invoke Application
It invokes an executable application only.Syntax
invokeapplication "Path of application"
SystemUtil
We can use this object to control applications and processors during Runsession.Syntax
SystemUtil.BlockInput
(Prevents keyboard & Mouse Input events from reaching the application)
CloseDescendentProcesses
Closes all processes opened by QuickTest
CloseProcessByHwnd
Closes a process that is the owner of a window with the specified handle.
CloseProcessById
Closes a process according to its Process ID (PID).
7/30/2019 QTP Class Notes 1
57/82
CloseProcessByName
Closes a process according to its name.
CloseProcessByWndTitle
Closes all processes that are owners of windows with the specified title.
Run
Runs a file or application.
UnblockInput
Re-enables keyboard and mouse input events after a BlockInput statement was
used to block them.
How to close a specified file
Ex:x = Window("Solitaire").GetROProperty("Hwnd")
systemutil.CloseProcessByHwnd (x)
Note
After every object .
After every variable
How to invoke specific webpage through specific browser?
Set ie=createobject("Internetexplorer.application")ie.visible = trueie.navigate "www.google.com"
How to close all the browsers at a time
Navigation
Tools Menu Options Web Tab Advanced Select Browser cleanup
under Run Time settings Ok Ok Put any script Run
How to close Popups during Run Timea=10
b=20 Setobj=createobject("wscript.shell")If b=a+10 Then
obj.popup "b is equal to a", 2 (Time in Seconds)elseobj.popup "b is not equal to a", 5
End If
7/30/2019 QTP Class Notes 1
58/82
How to count number of links in a specific webpage and how to display
their names one by one.
Set x=description.Create
x("micClass").value = "Links"
'set l = Browser("AXIN BANK").ChildObjects(x)Set l = Browser("AXIN BANK").Page("AXIN BANK").).ChildObjects(x)n=x.countFor i=0 to n-1 step 1
y=x(i).getroproperty("text")
msgbox y
Next
Spell Checks
Set mw=createobject("Word.application")
mw.visible = trueSet wl=description.Create
wl("micClass").value="Link"
m = Browser("AXIN BANK").Page("AXIN BANK").ChildObject(wl)y=m.countFor i=0 to y-1 step 1
op=m(i).GetROProperty("Text")
mw.wordbasic.filenew mw.wordbasic.insert
str
s=mw.activedocument.spellingerrors.count Ifs=0 Then
reporter.ReportEvent micPass,"No Mistakes were found","test is pass"elsereporter.ReportEvent micFail,"Mistakes in"&str, "Test is fail"
End If
mw.documents.close(false)
Next
mw.quit
7/30/2019 QTP Class Notes 1
59/82
Automation Object Model
To pre-configure QTP Test settings, we can use Automation Object Model
Open Notepad prepare the script like as below and save the file with *.vbs
extension
set qtp = Createobject("QuickTest.Application")
qtp.visible = true
qtp.launchqtp.activateview "expertview"qtp.showpanescreen "datatable", falseqtp.showpanescreen "debugviewer", Trueqtp.showpanescreen "activescreen", True
qtp.open "C:\Program Files\Mercury Interactive\QuickTest Professional\Tests\test7"
qtp.test.runqtp.quit
Actions
Action means a group of meaningful statements or a set of meaningfuloperations.
They are (3) Types, such as(i) Non-reusable Action
An action can be called by the test with which it is stored and
it can be called only once.(ii) Reusable Action
An action can be called multiple times by the test with whichit is stored and by other tests.
(iii) External Action
A reusable action becomes External Action when we call
that action from one test to another test.
Call to New Action
We can use this option to call a new action.Navigation
Insert Menu Call to New Action Enter Action Name [Optional] Check
Reusable Action or Uncheck Reusable Action Click Ok.
How to Delete Action
To delete action we can follow below navigation.Navigation:
Open Action which you want to delete Edit Menu Action Delete
Action Click Ok
7/30/2019 QTP Class Notes 1
60/82
How to rename
Action Navigation
Open Action which you want to rename Edit Menu Action Rename
Action (Shift + F2) Enter name of the Action Click Ok.
Call to Copy of ActionWe can use this option to call a copy of action from the current test or
from any other test.Code:
RunAction Copy of Action Name, oneiterationNavigation
Insert Menu Click on Call to Copy Action Select Test Select Action Click OkNote: If you call action using Call to Copy of Action option you can get
action with Read and Write permission.
Call to Existing Action
We can use this option to call Reusable Action from the current test orfrom another test.Note: If we call Reusable Action using Call to Existing Action option we can
get action with Read Only permission.Navigation
Insert Menu Click on Call to Existing Action Select test Select
Action Click on Ok.Syntax
RunAction Action Name[Test Name], oneiteration
Call to Win Runner
We can use this option to call Win Runner Test or function to QTP MainTest.Navigation
Insert Menu Call to Win Runner Action Browse Win Runner Test Path
Click Ok.
Split Action
We can use this option to divide one action into 2 Actions.Navigation
Open Action which you want to divide into 2 Actions Place the cursor atrequired position Edit Menu Action Split Action Enter meaningfulAction Names with description Select Option [Independent or each other or
Nested] Click Ok.
Automation Testing 59
7/30/2019 QTP Class Notes 1
61/82
Case Study (Frame Work)
Test 1 Test 2 Test 3Login Insert Update
Log in to AppLog in to App Log in to AppInsert Order Open Record
Logout Logout Update Record
Logout
Navigation
Record your required operations (Login; Open Record; Logout) Save the
Reusable Actions in Specified location
Take New test
Prepare the scriptfor above scenarios using those reusable actions Start Menu Programs QTP Test Batch Runner Batch Menu Add [Ins] Specify yourrequired Tests Click Run (F5).
Action Template
To create Action Template we can follow Navigation.
Open Notepad Enter your required information like asbelow. Project Name:
Module Name:Created By:
Created On:
***************************************************************
Save the file in dat Folder with file name as actiontemplate.mst Take Newtest (when ever you are using new test the above information will be added inthe top of the test as shown below.
7/30/2019 QTP Class Notes 1
62/82
Action Parameters
There are two types of Parameters (i) Input Parameter (ii) OutputParameterCase 1: How to pass data to the external action.
Test 1
RunAction Action1[Test2].oneiteration
Nagesh,mercury
Test 2
.setparameter (uid)
.setsecure crypt.encrypt (Parameter(pwd))
Navigation
Record Required operation Replace constant values in Parameter EditMenu Action Action Properties Parameters Tab Add Parameter[Enter Input Parameter Name same as in script] Ok Save Action NewTest Call that reusable Action using calling to existing action option Passvalues like as shown in the diagram.
Case 2: How to pass data from one action to another action.Action 1
Parameter (a) = 10
Action 2
.set parameter (a)
Navigation
Take Two Actions like as shown in the diagram in a same Test Open 1st
Action Edit Menu Actions Action Properties Parameters Tab AddOutput Parameter Name with Type (a, Any) Click Ok Open 2nd Action Edit Menu Actions Action Properties Parameters Tab Add InputParameter Name with type (a, Any) Click Ok Keyword View
Right Click on 1st
Action (Output) Action Call Properties ParameterValues Tab Enter variable in Store In field Click Ok Right Click on
2nd
Action (Input) Action Call properties Parameter Values Tab Entervariable in Store in field in input parameter Click Ok Expert View Run
Analyze Results manually
7/30/2019 QTP Class Notes 1
63/82
Environment Variables
Environment Parameters especially useful for localization testing (If youwant to test the application when the user interface strings are changingdepending on selection of different languages)
Environment parameters can be used for testing the same application on
different browsers.Environment Variables are (2) Types such as (1) Built-in-variable (2)
User defined variable.(1)Built-in-variable
It represents the information about the Test and the system inwhich the test is running.
Ex: Environment.Value ("OS") It will display Operating SystemEnvironment.Value ("OSVersion") It will display operating system versionEnvironment.Value ("LocalHostName") It will display Local Host NameEnvironment.Value ("Test Name") It will display Test Name
(2)User defined variable
There are (2) Types such as(i) Internal Variables
Internal Variables can be created in the Test and can be usedin any Action of the same test.
Ex: struid=environment.Value("uid")
strpwd=environment.Value ("pwd")SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"With Dialog("Login")
.Activate
.WinEdit("Agent Name:").Set struid
.WinEdit("Password:").SetSecure crypt.Encrypt (strpwd)
.WinButton("OK").Click
End With
Navigation
Records your required operation File Menu Settings Environment Tab Select variable type as User DefinedAdd Environment NamewithValue Click Ok Click Ok Replace constant values in the scriptwith environment variables likes as shown in the above script Click Run Analyze results manually
7/30/2019 QTP Class Notes 1
64/82
(ii) External Variables
External Variables will be present in the .xml file and wecan associate this xml file to the test to use those variables in anyaction of that test.
To create xml file with required variables we can prepare
script likes as below.
Open Notepad Prepare script like as below Save the file with
.xml extension.
uid
suresh
pwdmercury
How to load variables and values from external file before
execution Navigation
File Menu Settings Environment Tab Select Variable type as Userdefined Select load variables and values from external file Browse the
file path Click Ok.
How to load variables and values from external file during
Runtime Code
Environment.LoadFromFile Path of file
Note:
Built in variables are Read Only variables.
Random Number
We can use this option to pass Random Data.Syntax
.set RandomNumber (1,10)
Automation Testing 63
7/30/2019 QTP Class Notes 1
65/82
Functions
User defined Functions
Like as programming language VB Script is also allows you to create
User Defined Functions for repeatable operations.
To create User Defined Functions we can follow below syntax.
Public / Private Function Function_Name (Arguments)
StatementsEnd Function
Ex
Public function addition (x,y)z=x+yaddition = z
End Function'****************************************a=10
b=20
c=addition (a,b)msgbox c
How to create Library File
Navigation
Create required function for the required repeatable operations Select the
script Copy the Script Paste the script in Notepad Save the file with.vbs extension
How to associate library file to Test before executionNavigation
File Menu Settings Resources Tab Add Associated function library Browse file path Click Ok.
How to associate library file during Runtime
Syntax
executefile Path of file
64 Automation Testing
7/30/2019 QTP Class Notes 1
66/82
Case Study
Navigation
Record required operation as per scenario Create functions for them Takethe script into Notepad Save the file with .vbs / .qfl extension Resources
Menu
Object Repository
File Menu
Export local objects
Save thefile in specified location Save Take required Environment variable in.xml file New test Associate all files like library file, environmentvariable file [File Menu Settings Resources Tab Click on Add file Browse that library file Environment Tab Select User Defined as variabletype Select load variables and values from external file Browse File path
Click Ok] Repository file [Resources Menu Associate Repositories Click on Add file Browse the Repository file path Associate with action]
prepare the script using functions like as below.
Ex: How to associate all files before execution
struid=environment.Value ("uid")strpwd=environment.Value ("pwd")res=login(struid,strpwd)msgbox res
res1=insert()
msgbox res1
logout()
Ex 2: How to associate all files during Runtime
Option explicit Dimstruid,strpwd,res,res1executefile "C:\Documents and Settings\Sai Sarvani\Desktop\flightres.vbs"environment.LoadFromFile "C:\Documents and Settings\Sai Sarvani\Desktop\QTP\environment.xml"repositoriescollection.Add "C:\Documents and Settings\Sai Sarvani\Desktop\
QTP\objectrepository.tsr"struid=environment.Value ("uid")strpwd=environment.Value ("pwd")res=login(struid,strpwd) msgboxresres1=insert()
msgbox res1
logout()
Automation Testing 65
7/30/2019 QTP Class Notes 1
67/82
flightres.vbs
Function login (struid,strpwd)SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTestProfessional\ samples\flight\app\flight4a.exe"
With Dialog("Login").WinEdit("Agent Name:").Set struid.WinEdit("Password:").SetSecure crypt.Encrypt(strpwd).
WinButton("OK").Click End With
If Window("Flight Reservation").Exist Thenreporter.ReportEvent micPass,"Login Successful","Test is
Pass"login = "Pass"
elsereporter.ReportEvent micFail,"Login Unsucessful","Test is fail"login=fail
EndIfEndFunction'**************************************************************
**Function insert()With Window("Flight Reservation")
.Activate
.WinMenu("Menu").Select "File;New Order"
.ActiveX("MaskEdBox").Type "090909"
.WinComboBox("Fly From:").Select "Denver"
.WinComboBox("Fly To:").Select "Frankfurt"
.WinButton("FLIGHT").Click
.Dialog("Flights Table").WinList("From").Select 3
.Dialog("Flights Table").WinButton("OK").Click
.WinEdit("Name:").Set "Suresh"
.WinEdit("Tickets:").Set "3"
.WinButton("InsertOrder").Click End withwait (10)x = Window("Flight Reservation").ActiveX("Threed Panel
Control").GetVisibleText() y="Insert Done..."
7/30/2019 QTP Class Notes 1
68/82
If strcomp(x,y,1)=0 Thenreporter.ReportEvent micPass,"Data inserted sucessfully","Testis Pass"insert=Passelse
reporter.ReportEvent micFail,"Data not inserted","Test is fail"insert=fail
EndIfEndFunction'****************************************************************Function logout()
Window("Flight Reservation").Activate Window("FlightReservation").WinMenu("Menu").Select "File;Exit"End Function
Debug
i) Pause
ii) Step Into(F11)
iii) Step Over (F10)
iv) Step Out (Shift + F11)
v) Run to Step (Ctrl + F10)
vi) Debug from Stepvii) Add to Watch (Ctrl + T)
viii) Insert / Remove Breakpoint (F9)
ix) Enable / Disable Breakpoint (Ctrl + F9)
x) Clear all Breakpoint (Ctrl + Shift + F9)
xi) Enable / Disable all Breakpoints
7/30/2019 QTP Class Notes 1
69/82
i) Step InTo (F11)
We can use this option to execute one line of statement, ifthe statement is function call or action call, then it will step into
Function or Action.
ii) Step Out (Shift + F11)
We can use this option to execute remaining statements in
the function of Action from the position of pointer [ ]
L
Recovery Scenario ManagerTo recover from unexpected events and errors that are occurred in the testenvironment during run session, we can use Recovery Scenario Manager.For good recovery, error must be known the occurrence is unknown.There are (4) Types of events such as(i) Application Crash
An open application fails during Test Run.
Navigation
Resources Menu Recovery Scenario Manager Click New Click Next
Select Application Crash as Trigger event Next Select selected executableapplication Next Select Recovery Operation [Keyboard, Mouse Operation,Close Application Process, function Call, Restart, Microsoft Windows]Next If
7/30/2019 QTP Class Notes 1
70/82
you want to check Add another operation else uncheck Next Next Enter
Scenario Name Next Select Option Finish Close Save the scenario inspecified location with .qrs
qrs stands for QuickTest Recovery Scenario.
(ii) Popup Windo
Recommended