SlideShare a Scribd company logo
1 of 96
http://www.qtpskills.com/p/qtp-chapter-iii.html
QTP - Chapter I
Introduction of Automation
Testing: - Testing is the process of improving the quality of software.
Ways to testing: -
Manual testing
Automation testing
Manual Testing: -
It is a process where we complete all the phases of STLC (software testing life cycle) by manual, is called
as manual testing
Draw backs of manual testing: -
Time consuming
More number of human resources are required
Tiredness of the testers
Human errors (Less accuracy)
Simultaneous actions are almost impossible
Automation Testing:-
Automation testing is a process where we can test the application with the help of Automation Tool
Benefits of Automation Tool:-
Fast: - It runs the script faster than human beings.
Reusable: - We can reuse the scripts in different regression testing.
Cost reduction: - It reduces number of resources and hence less budget.
Accuracy: - No tiredness and hence good accuracy results.
Disadvantage of Automation Testing:-
Proficiency is required to write automation test scripts.
It is expensive to buy.
In all areas automation testing is not possible.
Difference between Manual and Automation Testing:-
Manual Testing:-
1. Testing is implemented by manually
2. 2. It is the best suite for application which the numbe of test cycles are less
3. The test case development is less
4. The test case execution time is more
5. The test data needs to be provide by manually
6. The test reports can be generated by manually
7. Defects need track manually
8. Organization point: the cost of manual testing is more
9. The programming knowledge is optional
Automation Testing:-
1. Testing is implemented by using tools
2. It is the best suite for application which number of test cases less
3. Test script development time more
4. Test script execution is time is less
5. The test data can be generated by tool it self
6. The test cases can be generated by automatically
7. Defects can be tracks automatically
8. the cost of automation testing is more
9. A minimum programming knowledge is required
Types of testing can be done by Automation: -
Functional (Positive and Negative) testing
Regression Testing
Performance Testing
Usability Testing
Functional Tools:-
Quick Test Professional (QTP)
IBM rational functional tester
Winrunner
Selenium
Test complete
Performance tools:-
Load runner
J meter
Test complete
Test Management Tools:-
Test direct
Quality center
Bugzilla
Rally
Clear quest
Things to done before Automation Testing: -
1. Return on investment (ROI)
2. Tool selection
3. Identify Framework
4. Automation feasibility
Automation feasibility: -
It is a process of identifying what test case can be automated and cannot be automated.
This will be done by automation tester for their respective modules.
What test case can be Automated: -
The test case needs to be run on every build
The test case needs to be run on multiple test data
Multiple browser compatibility test cases
Application objects which do not change in short time
What test case cannot be Automated: -
Security related test cases
Idle time functionalities
Batch processing requirements
Graphs related test cases
Usability test cases
Documentation verification testing
3rd party objects requirements. Ex: - PDF, Printers etc...
> After completion of Automation feasibility we go for estimations
Example: - Finding number of resources to automate for 800 test cases in 100 days
Number of test cases to designed per day = 800/100=8 test
One resource 2 scripts per day
How resources need if 8 scripts per day =8/2=4 resources
Example: - Finding number of days to automate 800 test cases with 4 resources
One resource 2 scripts/ day
4 resources 4*2=8 scripts/day
Number of days = Total test cases/per day scripts= 800/8=100 days
Automation testing process: -
1. ROI [Return on Investment]
2. Tool selection
3. Test cases feasibility analysis
4. Preparation of automation test plan document
5. Framework designing
6. Designing test scripts for manual test cases
7. Involve in code walkthroughs and code inspections
8. Test scripts debug
9. Involving in regression support by executing test scripts as a batch
10. User acceptance testing
QTP Automation Chapter II
Introduction to QTP (Quick Test Professional)
Type of Tool: - it is a functional Regression Testing Tool
Earlier Version: -
5.5 Released in 2001
6.0 Released in 2002
6.5 Released in 2003
7.0 Never Released
8.0 Released in 2004
8.2 Released in 2005
9.2 Released in 2007
9.5 Released in 2007
10.0 Released in 2009
11.0 Released in 2011(this version
is called as UFT: - Unified
Functional Tester)
11.5 Beta version 24/12/2012
Scripting Language: - VB script, java script, Perl script
Note: - While latest versions of QTP supports all most all versions.
License in QTP: -
Seat license: - it is 1:1 license (this is single user license)
Concurrence license: - This is a network based license which can share by all the machines in net work.
Launching QTP: -***
Step 1: - currently we are using client license, so we need to connect to the client machines.
We can connect to the client machine with help of Citrix access get way/ VAP/ Remote Desktop (MSTSC)
Step 2: - Click on start > All Programs > Quick Test Professional > select Quick Test Professional
Step 3: - While lunching QTP it verifies QTP license and add-in license
Step 4: - It Opens add- in Manager Windows with add-ins
Step 5: - Select required add- in and click ok button.
Add-in Manager: -
> It displays all the available add-ins, by default Quick Test Professional provides ActiveX, VB, and Web
Note: -by default QTP supports windows environment and hence it is not showing is add-in manager
window.
> Add-in manager is used to select required environment (Add-in) to make compatible with required environment.
> Apart from all this add-ins, if user wants any extra add-ins then user need buy from HP and install.
Architecture of QTP: -
QTP window is divided in to bellow parts.
1. Test Pane
2. Active Scripts
3. Data Table
4. Information Pane
5. Debug viewer Pane
6. Missing resource Pane
7. Tool option
1. Test Pane: - It is an area where we can write a new test script or to open existing test scripts.
It is divided in to 2 views
1> Expert view: - It displays test script in VB Script format
2> Keyword view: - it displays test script in GUI format.
It is divided into bellow views
1. Item: - displays fields names
2. Operation: - Displays operation names (Actions performed)
3. Value: - it displays test data.
4. Documentation: - it displays a sentence about item, operation and value.
Note 1: - If we do any operation in expert view it effects to keyword and vice versa
Note 2: - If we have any syntax errors in expert view not able to navigate to keyword view
Note 3: - We can also design test scripts from keyword view.
2. Active Screen: - it is displays a screen shot for each and every VBScript statement. (view menu --> Active
Screen)
3. Data Table: - It holds multiple Test Data. It is looks like ms-excel sheet (it contains 65, 536 rows and 256
columns). By default data table provides following 2 sheets 1.Global, 2. Action1
4. Information Pane: - (Navigation:- view menu--> Information )
> It displays syntax error massages. When we save test script.
Note: - After save a test script QTP internally compiles the script and display syntax errors in information pane
> Information pane contains bellow information
Details: - It displays syntax error information
Item: - It displays script name
Action: - It displays Action name
Line no: - It displays error line number
5. Debug viewer Pane: - It is used to find the logical errors and variable values during script execution
debug viewer) (view
6. Missing resource: - It displays not available file path which we associated to test script.
7. Tool option: - these are menu options where we can select required menu options.
QTP Chapter III
Introduction to VBScript
Display user defined message:
MsgBox Function: -It displays given message and waits for the user to click OK button or close dialog
Ex: - MsgBox “Welcome to QTP World”
Comments in QTP: - By using single cots („) user can give the comments for scripts
Display Message with Required Dialog Title and Buttons: -
Syntax: -MsgBox “<message>”, button no, “<dialog title>”
Ex: -MsgBox “Welcome to QTP World”, 0 “sample”
Here: - 0 is the number for the different types of buttons we have 0, 1, 2, 3, 4, 5, 16, 32…etc. go to
MsgBox help by pressing function1 (F1).
“Sample” is dialog title.
Print Statement: -
It displays user given message in Quick Test Print Log window
It doesn‟t require any user interaction
It will works in QTP only
Note: - MsgBox is defined in VBScript
Print statement defined in QTP
Display a message and Close: -**
Set obj= CreateObject (“Wscript.Shell”)
obj.Popup “Welcome to QTP World”, 5, “Sample”
Here: - number 5 is seconds to close the popup
Reading Values during runtime: -
InputBox: -it displays a prompt and waits for the user, to enter text and click OK/ Cancel button
Syntax: - <variable>= InputBox (“<message>”)
Ex: - Val = InputBox (“Enter any Value”)
MsgBox Val
Operators: -
Types of VBScript Operators: -
1. Arithmetic Operators
2. Assignment Operator
3. Comparison Operator
4. Concatenation Operators
5. Logical Operators
Arithmetic Operators: -
These are used to perform Mathematical operations on given values.
1. ^ operators: -It raises a number to the power of an exponent
Ex: - MsgBox 2^3 „returns 8 (2*2*2)
2. * operators: - Multiplies
Ex: - MsgBox 2*3 „returns 6
3. / operators: - divides
Ex: - MsgBox 2/3 „returns 0.5(Float value)
4.  operators: - divides
Ex: - MsgBox 2/3 „returns 0(Integer value)
5. MOD operators: - divides
Ex: - MsgBox 7 mod 5 „returns 2 (7 divided by 5)
6. + operators: - Sum of given number
7. - operators: - Finds difference between given number
Assignment Operator: -
= operator: - assigns a given value to a variable
Ex: - Val = 10
MsgBox Val
Comparison Operator: -
These are used to compare two given values
Ex: - Val1=10
Val2 = 20
MsgBox Val1 < Val2 „Returns True
MsgBox Val1 > Val2 „Returns False
MsgBox Val1 <> Val2 „Returns True
MsgBox Val1 = Val2 „Returns False
Concatenation Operator: -
& operator: -It concatenates/ appends to given values
Ex: - Val1= “Hi”
Val2 = “Bye”
MsgBox Val1 & Val2 (Without space)
MsgBox Val1 &” ” & Val2 (With space)
Logical Operator: -
AND operator: - Perform logical conjunction on 2 given conditions
OR operator: - Perform logical disjunction on 2 given conditions
NOT operator: - Perform logical disjunction on 2 given conditions
If….Then….Else….If: -
Maintaining conditional statement, in another conditional statement
Syntax: - If<condition> Then
<Statement>
Else
If<condition>Then
<Statement>
End If
End If
Ex: - Apply If….Then….Else….If to bellow scenario,
Do you know testing tool course. If yes then find do you know QTP. If QTP know then display a message
Try for JOB. If QTP doesn‟t know then display a message “Go to login f1 to learn QTP”. If testing tool
doesn‟t know then display a message “Got login f1 to learn TT”.
Val2 = InputBox ("Do you know Testing Tools?")
If Val2="yes" Then
Val3= InputBox ("Do you know QTP?")
If val3="yes" Then
MsgBox "Try for job"
Else
MsgBox "Go to login F1 to learn QTP"
End If
Else
MsgBox "Go to Login F1 to learn TT"
End If
Select….Case: -
It is used to execute a group of statements depends on multiple conditions
Syntax: -
Select Case <variable>
Case 1 <condition>
<Statement>
Case 2 < condition >
<Statement>
Case 3 < condition >
<Statement>
Case Else „Optional
<Statement>
Ex: -Display one number and display a day name
Val = InputBox ("Enter any number")
Select Case Val
Case 1
MsgBox “Sun Day"
Case 2
MsgBox "Mon Day"
Case 3
MsgBox “Tue Day"
Case 4 MsgBox "Wed Day"
Case 5 MsgBox "Thu Day"
Case 6 MsgBox "Fri Day"
Case 7 MsgBox "Sat day"
Case Else MsgBox "Invalid Number"
End Select
Variable Declaration: -
Variable: -It is a storage place where we store variable.
Declaration: -We declare the variable by using DIM statement.
Dim Var1, Var2…
Note: - ****
1. Variable names should be meaning full
2. Variable name should explain what type of data we are storing in it
Ex: -
If store INTIGER then we starts with „i‟
If store STRING then we starts with„s‟
If store DOUBLE then we starts with„d‟
If store BOOLEAN then we starts with „b‟
If store DATE then we starts with „dt‟
If store TIME then we starts with„t‟
3. Variable names are not case sensitive but we follow standards
4. Variable names starts with small latter, if it contains multiple words then second word on wards the first latter
should be a capital latter
Ex: -Dim sEmpName, dEmpSal, dtDob, iEmpId….
5. Default variable is EMPTY
6. When we give the values (numbers) from InputBox for „+‟ operator it treats as String Integer and concatenates
the values. For „-„, „*‟, „/‟ operators converts the numbers from String Integers into integer values and do the
mathematical operations
7. VBScript variables are variant data type (any kind of data)
Ex: -Variable: -
MsgBox Krishna + sreekar „Returns 0 (zero)
MsgBox Krishna - sreekar „Returns 0 (zero)
MsgBox Krishna * sreekar „Returns 0 (zero)
MsgBox Krishna / sreekar „Returns Overflow error Massage
Strings: - MsgBox “Krishna” + “sreekar” „Returns Appends / concatenates the strings
MsgBox “Krishna” - “sreekar” „Returns Error msg as not able to perform String subtraction
MsgBox “Krishna” * “sreekar” „Returns Error msg not able to perform String Multiplication
MsgBox “Krishna” / “sreekar” „Returns Error msg not able to perform String Division
Strings and Variable: -
MsgBox “Krishna” + sreekar „Returns krishna
MsgBox “Krishna” - sreekar „Returns Error
MsgBox “Krishna” * sreekar „Returns Error
MsgBox “Krishna” / sreekar „Returns Error
String Integers: -
MsgBox “10” +”20” „Returns 1020- appends/ concatenates
MsgBox “10” -”20” „Returns -10
MsgBox “10” *”20” „Returns 200
MsgBox “10” /”20” „Returns 0.5
String Integers and Numbers: -
MsgBox “10” + 20 „Returns 30
MsgBox “10” - 20 „Returns -10
MsgBox “10” * 20 „Returns 200
MsgBox “10” / 20 „Returns 0.5
String and Numbers: -
MsgBox “krishna” + 20 „Returns Error Massage
MsgBox “krishna” - 20 „Returns Error Massage
MsgBox “krishna” * 20 „Returns Error Massage
MsgBox “krishna” / 20 „Returns Error Massage
In VBScript declaring variables are not mandatory, But we are declaring
[Q: - Is variable declaration is mandatory in VBScript? answer is no then next...Q: - Why?]
Option Explicit: -***
It displays error massage for undefined variable names. Option Explicit is must declared in the first line of the
program.
Ex: -
OptionExplicit
Dim sEmpname
sEmpName “sreekar”
MsgBox sEName „Returns Error Massage for not defined sEName variable
Note: - Variable names should not be a KEY word
Loop Statement: -
These are used to execute a group of statements for multiple times
VBScript Loop Statements: -
1. For… Next
2. While… Wend
3. Do… Loop
For…Next: - It executes a script for required number of given times
Syntax: - For <variable> = <Start Position > To < End Position > [Step]
<Statement>
[ExitFor]
Next
{Here written in [] are optional}
Ex: - Display a massage “QTP” for 5 times
For index = 1 To 5
MsgBox index
Next
> In bellow code a and z treats as variable returns empty values so answer is 0
For index = a To z
MsgBox index
Next
> In bellow code a and z treats as variable returns empty values so answer is 0
For index = “a” To “z”
MsgBox index „Returns error massage
Next
Ex: - Display numbers from 5 to 10
> In bellow given string integers are converts in to integers
For index = “5” To “10”
MsgBox index
Next
STEP Command:
Ex: -
For index = 1 To 5 Step 3
MsgBox index „Returns 1, 3
Next
Ex: - Display even numbers 2 to 10
For index = 2 To 10 Step 2
MsgBox index „Returns 2, 4, 6…
Next
Ex: - Display odd numbers from 1 to 10
For index = 1 To 10 Step 2
MsgBox index „Returns 1, 3, 5…
Next
Ex: - Display numbers from 5 to 1
For index = 5 To 1 Step -1
MsgBox index „Returns 4, 3…
Next
ExitFor: -
Ex: - For index = 1 To 10 Step 2
MsgBox index „Returns 1 and exits from For loop
ExitFor
Next
Ex: - For index = 1 To 10 Step 2
MsgBox index
If index = 3 Then
ExitFor
EndIf
Next
While… Wend: - It execute group if statements until condition is True
Syntax: -
While <condition>
<Statement>
Wend
Ex: - Display a massage “QTP” for 5 times
index = 1
While index <= 5
Print "QTP"
index = index+1
Wend
Ex: -Display numbers from 1 to 10
index = 1
While index <= 10
Print index
index = index+1
Wend
Ex: - Display odd numbers from 1 to 10
index = 2
While index <= 10
Print index
index = index+2
Wend
Do… Loop: - It executes group statement until condition becomes True
Syntax: - Do <condition>
<Statement>
Loop While <condition>
Ex: -Display a massage “QTP” for 5 times
index = 1
Do
Print "DTP"
index = index+1
Loop While index = 5
Ex: -Display numbers from 1 to 10
index = 1
Do Print index
index = index+1
Loop While index <= 10
Functions
Functions are used for scripts reusability
1. Built-in Functions
2. User Defined Functions
Built-in Functions: -
These are pre defined by VBScript
Access functions in QTP
Category as Functions Library as Built-in Function find the functions in StepGenerator Insert
MenuOperation drop down
Note 1: - Function names are not Case Sensitive
Note 2: - We follow standards like function name starts with capital later if it contains multiple words then 2nd word
on words 1st later should be a capital latter
1. Abs() [Absolute]: -It returns absolute value to a given number
Ex: - MsgBox Abs (10) „Returns 10
MsgBox Abs (-10) „Converts the –ve in to +ve „Returns 10
MsgBox Abs (10.56) „Returns 10.56
MsgBox Abs (-10.56) „Returns 10.56
MsgBox Abs ("10") + Abs ("20") „Returns 30 – Converts the string into Integer Value
2. Asc(): - It returns ASCII to given Character
Ex: -MsgBox Asc ("a") „Returns 97
MsgBox Asc ("z") „Returns 122
MsgBox Asc ("A") „Returns 65
MsgBox Asc ("Z") „Returns 90
3. Chr(): - It returns ASCII to given Character
Ex: - MsgBox Chr (97) „Returns a
MsgBox Chr (122) „Returns z
MsgBox Chr (65) „Returns A
MsgBox Chr (90) „Returns Z
4. CInt(): - It Converts String Integer in to Integer
Ex: - iVal1 = "10"
iVal2 = "20"
MsgBox iVal1+iVal2 ' Returns 1020
MsgBox CInt (iVal1) +CInt (iVal2) ' Returns 30
Ex: - 10.56 the CInt Converts into 11
iVal1= "10.56"
iVal2= "-20.78"
iVal1= iVal1*100
iVal2= iVal2*100
MsgBox (iVal1+iVal2) / 100
5. CStr(): - It converts given value into Strings
iVal1 = 10
iVal2 = 20
MsgBox iVal1+iVal2 Returns 30
MsgBox CStr (iVal1) + CStr (iVal2) „Returns 1020
MsgBox CStr (iVal1) – CStr (iVal2) „Returns -10
Date and Time Factions
6. Date: - It returns current system Date in MM/DD/YYYY format
Ex: - MsgBox Date
7. Time: - It returns current system Time in HH/MM/Sec format
8. Ex: - MsgBox Time
9. Now(): - It returns current system Date & Time
Ex: - MsgBox Now
10. DateAdd(): - This function add/ subtracts given date or time, given date and time
Ex: - MsgBox DateAdd ("yyyy", 1, Date) „Returns Year with adding 1 to the current year
MsgBox DateAdd ("q", 1, Date) „Returns Quarter with adding 1 to the current Quarter
MsgBox DateAdd ("m", 1, Date) „Returns Month with adding 1 to the current Month
MsgBox DateAdd ("y", 1, Date) „Returns Day of year with adding 1 to the current Day of year
MsgBox DateAdd ("d", 1, Date) „Returns Day with adding 1 to the current Day
MsgBox DateAdd ("w", 1, Date) „Returns Weekday with adding 1 to the current Weekday
MsgBox DateAdd ("ww", 1, Date) „Returns Week of year with adding 1 to the current Week of year
MsgBox DateAdd ("h", 1, Date) „Returns Hour with adding 1 to the current Hour
MsgBox DateAdd ("n", 1, Date) „Returns Minute with adding 1 to the current Minute
MsgBox DateAdd ("s", 1, Date) „Returns Second with adding 1 to the current Second
MsgBox DateAdd ("yyyy", 8000, Date) „Returns Error because year above 10000
11. DateDiff (): - This function is used to find the difference in between given 2 dates or 2 times. In day, Month,
Year, hour, Minutes, Seconds intervals
Syntax: -MsgBox DateDiff (Interval, date1, date2)
MsgBox DateDiff ("d", Date,"01-01-2013") 'Returns -2 (My System date 03-01-2013)
MsgBox DateDiff ("d", "01-01-2013", Date) 'Returns 2 (My System date 03-01-2013)
12. DatePart(): - It is used to retrieve required interval date or time from given date or time
Syntax: - MsgBox DatePart (Interval, Date/ Time)
MsgBox DatePart (“d”, Date)
MsgBox DatePart (“m”, Date)
MsgBox DatePart (“yyyy”, Date)
13. Day(): - It retrieves day from given date
Ex: - MsgBox Day (Date)
14. Month(): - It retrieves Month from given date
Ex: - MsgBox Month (Date)
15. MonthName(): - It retrieves the name of the month from given number from 1 to 12
Ex: - MsgBox MonthName (Date)
16. Year(): - It retrieves Year from given date
Ex: - MsgBox Year (Date)
17. WeekDay(): - It retrieves Weekday from given date
Ex: - MsgBox WeekDay(Date)
18. WeekDayName(): - It retrieves WeekDayName from given number(1-7)
Ex: - MsgBox WeekDayName (1) „Returns Sunday
MsgBox WeekDayName (WeekDay (Date)) „Returns current WeekDayName
Boolean Functions: -
19. IsDate (): -It retrieves Boolean value for given expression is date or not. It returns True if given value is date
else false
Ex: - MsgBox IsDate (“Suresh”) „Returns False
MsgBox IsDate (“3-01-2013”) „Returns True
20. IsEmpty (): -It retrieves Boolean value for given value is Empty or not. It returns True if given value is Empty
else false
Ex: - Dim val1, val2, val3
Val1 = 10
Val2 = Null
MsgBox IsEmpty(Val1) „Returns False
MsgBox IsEmpty(Val2) „Returns False
MsgBox IsEmpty(Val3) „Returns True
21. IsNull (): -It retrieves Boolean value for given value is Null or not. It returns True if given value is Null else
false
22. IsObject (): - It retrieves Boolean value for given expression is Object or not. It returns True if given value is
Object else false
Ex: - Dim Val1, Obj
Val1 = 10
Set obj = CreateObject (WScript. Shell)
MsgBox IsObject (Val1) „Returns False
MsgBox IsObject (Obj) „Returns True
23. IsNumeric (): - It retrieves Boolean value for given expression is Numeric or not. It returns True if given value
is Numeric else false
Ex: - Dim val1, val2, val3
Val1 = 10
Val2 = 13.45
Val3= “suresh”
MsgBox IsNumeric (Val1) „Returns True
MsgBox IsNumeric (Val2) „Returns True
MsgBox IsNumeric (Val3) „Returns False
String Functions
24. Left (): - It returns number of characters from left side of a given string
Ex: - sString = “My Name is Suresh”
MsgBox Left (sString, 4) „Returns My N
25. Right (): - It returns number of characters from right side of a given string
Ex: - sString = “My Name is Suresh”
MsgBox Right (sString, 4) „Returns resh
26. Mid (): -*** It returns a substring from a given String
System: - MsgBox Mid (String, start position [, Number of characters])
Ex: - Ex: - sString = “My Name is Suresh”
MsgBox Mid (sString, 4, 7)
MsgBox Mid (sString, 4)
MsgBox Mid (sString, 100)
MsgBox Mid (sString, 100, 1)
sString = "Rs:1000/-"
MsgBox Mid (sString, 4, 7) ' Returns 1000/-
MsgBox Mid (sString, 4, 4) ' Returns 1000
'To get any number
MsgBox Mid (sString, 4, Len (sString)-5) ' Returns 1000
27. Len(): - ***It returns number of characters from given string
Ex: - sString = “My Name is Suresh”
MsgBox Len (SString)
28. Replace(): - This function is used to replace a text with another text in given text
Syntax: - Replace (String, replacing text, new text)
Ex: - sString = "My name is suresh"
MsgBox Replace (sString, "suresh", "babu")
MsgBox Replace (sString, "is", "")
29. LTrim(): - It removes all spaces from Left side of a given string [Ex: - MsgBox LTrim(sString)]
30. RTrim(): - It removes all spaces from Right side of a given string [Ex: - MsgBox RTrim(sString)]
31. Trim(): - It removes all spaces from Left and Right side of a given string
32. LCase(): - It converts given text in lower case letters
33. UCase(): - It converts given text in upper case letters
Ex: - MsgBox LCase (“My Name Is SURESH”)
MsgBox UCase (“My Name Is SURESH”)
34. StrReverse(): - ***It displays / retrieves a reverse text for given string/ text
sString= “suresh”
MsgBox StrReverse (sString)
Without using StrReverse:-
Dim sString
sString = “suresh”
For index = Len (sString) To 1 Step -1
str = str & Mid(sString, index,1)
Next
Print str
35. InStr() and InStrRev(): - It retrieves the first occurrence position of the given text in actual text
sString = “My name is suresh your name is babu”
MsgBox InStr (sString,”suresh”) „Returns the position of„s‟ from suresh
MsgBox InStr (sString,”name”) „Returns 4 first occurrence of name
MsgBox InStr (sString,”babu”) „Returns 0
MsgBox InStrRev (sString,”name”) „Returns 24 Last occurrence of name
MsgBox InStr (14, sString,”babu”) „Returns 0: suresh is not found from 14th position
36. StrCompp(): - It is used to compare two given strings
37. String(): - It is used to display the string in number of times
Ex: -MsgBox String (5, *) „Returns *****
38. TypeName(): -It returns the data type for the given variable
Ex: - Dim Val
Val = 10
MsgBox Val 'Returns 10
MsgBox TypeName (Val) 'Returns Integer
Val = 10.05
MsgBox Val 'Returns 10
MsgBox TypeName (Val) 'Returns Double
Val = "Suresh"
MsgBox Val 'Returns 10
MsgBox TypeName (Val) 'Returns String
39. Split (): - It is used to split the text with given delimiters
40. Arrays
Arrays are used to store multiple values in a variable
Declaration: -
1> Static Array declaration
Dim sName (3)
2> Dynamic Array declaration
Dim sName ()
Scripts
9. Write a script to find the SUM of odd number up to given number
10. Write a script to find the SUM of even number up to given number
11. Write a script to find given Text/ Numbers is palindrome or not [madam reverse madam]
sString = UCase(InputBox("Enter the String/Number:"))
rString = StrReverse(sString)
If StrComp (sString,rString) = 0 Then
MsgBox “It is a Palindrome"
Else
MsgBox “It is Not a Palindrome"
End If
12. Write a script to find Factorial of given number [5*4*3*2*1=120]
Option Explicit
Dim iVal1 ,iVal2, iFact
iVal1= Int (InputBox ("Enter a Number :"))
iFact = 1
iVal2=1
Do while iVal2 <=iVal1
iFact = iFact * iVal2
iVal2=iVal2+1
Loop
Print iFact
15. Write a script to display * as bellow with respect to given value
Option Explicit
Dim iVal, sString,index,index1
sString=""
iVal = 5 ' InputBox ("Enter a Number")
For index = 1 To iVal
For index1 = 1 To index
sString = sString & " * "
Next
Print sString
sString=""
Next
16. Write a script to display * as bellow with respect to given value
17. Write a script to display * as bellow with respect to given value
9 programs to write for this
1) Pro1
Option Explicit
Dim iVal, sString,index,index1
sString=""
iVal = 5 ' InputBox ("Enter a Number")
For index = iVal To 1 Step-1
For index1 = 1 To index
sString = sString & " * "
Next
Print sString
sString=""
Next
2) Pro 2
Option Explicit
Dim iVal, sStar,index,index1,iSpace
iVal = 5
For index = iVal To 1 Step-1
For index1 = 1 To iSpace
sStar= sStar & " "
Next
For index1 = 1 To index
sStar = sStar & "*"
Next
Print sStar
sStar ="" ' Removing the value after print
iSpace= iSpace + 1' Increasing the spaces for next iteration
Next
'#############################################################################################
'######### Program to write a character in a particular pattern using VBS #########################
'#############################################################################################
'Declaring variables
Dim MainCounter,TempCounter,sStr,sTempStr,sMainStr,PatternChar
'Initializing variables
PatternChar = "*"
sStr = ""
'Reading from Input and initializing
MainCounter = InputBox("Enter any number")
If MainCounter = "" Then
MainCounter = 9
End If
MainCounter = Abs(MainCounter)
TempCounter = MainCounter
'Looping twice the supplied value to draw the pattern and reverse it
For MainIndex = 1 to MainCounter * 2
'Increase the tempCounter for drawing the pattern and
'Decrease the tempcounter to draw the pattern in reverse order
If Abs(MainIndex) <> 1 and Abs(MainIndex) <> MainCounter + 1 Then
If MainIndex <= MainCounter Then
TempCounter = Abs(TempCounter) - 1
Else
TempCounter = Abs(TempCounter) + 1
End If
End If
sTempStr = ""
iSpace = ""
'Looping to Create the pattern for a single row
For indx = 1 to TempCounter
sTempStr = sTempStr & PatternChar
Next
'manipulating space for a row
iSpace = Space((Abs(MainCounter)-Abs(TempCounter)) * 2)
'Adding the space for a single row
sStr = sStr & sTempStr & iSpace & sTempStr & vbNewline
Next
'sStr= sStr & vbNewline & StrReverse(sStr)
'MsgBox sStr
'Writing the pattern to a txt file in D drive
Dim filesys, testfile
Set filesys = CreateObject("Scripting.FileSystemObject")
Set testfile= filesys.CreateTextFile("d:PatternDrawnFromVbs.txt", True)
testfile.WriteLine sStr
testfile.Close
Example: - write a script to retrieve India in given string “I love India”
sVal = "i love InDiA"
sVal = Split(s," ")
MsgBox sVal(UBound(s))
Application (Window, VB, Java, Dot Net, Web) Script
Application Script: -
Script 1: -Write a script to enter student details
Note: - Before writing a VBScript with respect to application we need to know bellow 5 information‟s
1. Object Name
2. Object Class Name
3. Object Parent Object Name
4. Object Parent Object Class name
5. Method Name. To perform operation
Note: - Object SPY To know about the object use Object SPY in TOOL MENU
For Web Application
iHwnd = Browser("Gmail")GetROProperty("hwnd") „ first 2 lines to activate the browser
Window("hwnd:="&iHwnd).Activate
Browser("Student").Page("Student").WebEdit("").Set "Sreekar"
Browser("Student").Page("Student").WebEdit("Course").Set "QTP"
Browser("Student").Page("Student").WebButton("Submit").Click
QTP Chapter IV
Chapter - 4
Object Repository: -
It is a storage place, where we store objects and their information
Note: - Before designing or executing a test script we need to add objects to Object Repository for recognition of
objects by QTP. Else QTP is not able to understand the objects displayed the errors while executing the script
Object Repository select Navigation: - Resource menu
Or Click Object Repository
Or Cntrl + R
Application under test [AUT]: -It means which application we need to test is called AUT.
Adding Objects to Object Repository: -
We can add objects to Object Repository by manually or by Recording
Adding Objects to Object Repository By Manually: -
Click Ad Objects to local icon Open Object Repository Open Application under test [AUT]
Select required object with the help of handler pointer
If it is parent object displays Filter Options [Selected objects only, Default Object Click OK button
Select required option Click OK Button. Types, All Object Types, Selected Object Types]
Note: - Every Action maintains individual Object Repository in Object Repository
Options in Object Repository: -
We have Operations as follows
ADD: - We can add objects to Object Repository by manually or by Recording
Select Rename Right Click on required object Rename: - Open Object Repository
Check YES in Select Delete Right Click on required object Delete: - Open Object Repository
Confirmation
Note-1: - Before executing the script, we make sure that the AUT is open
Note-2: - If we Re-name the Object name in Object Repository it affects to test script
Note-3: - If we do any modification on objects in test script it will not/ doesn‟t affect to Object Repository
Note-4: - If we save a test script Object Repository also saves for the same test script
Note-5: - We can drag objects from Object Repository to test script. We write test script in Keyword View.
Types of Object Repository: -
We have two types of Object Repository
1. Local Action (or) per Action Object Repository
2. Shared Object Repository
Local Action (or) per Action Object Repository: -
Maintaining Repositories in Action independent is called as Local Action (or) Per Action Object
Repository.
Ex: - A1R (Action Repository) Objects
Objects >A2R (Action Repository)
Objects >A3R (Action Repository)
Note1: - Local repository saves the file with “.mtr” [Mercury Test Repository] while save the script
Shared Objects Repository: -
Creating and maintaining a single repository for multiple actions called as
Shared Object Repository. EX: -
Creating Shared
Creating Shared Object Repository: -
Export Local File Add object to Object Repository Open Object Repository Open AUT
Save the file in required path with “.tsr” [Test Shared Repository] Objects
After creating a shared ObjectRepository we need to associate to required test script for use.
We can associate in bellow ways
1. By Navigation
2. By Scripting
By Navigation: -
Browse and Open Click Add Button Associate Repositories Repository Open required test script
click OK button select Required Action SOR [Shared Object Repository]
By Scripting: -
Syntax: - RepositoriesCollection.Add “SOR File Path”
Ex: - RepositoriesCollection.Add “D:sureshORxxxx.tsr”
Note1: - RepositoriesCollection.Add is a static association i.e. if we write the statement in action, then it associate to
action1 Repository
Note2: - After script execution SOR disassociate by default.
Note3: -For better maintenance we use only one shared object repository.
Working with Shared Object Repository/ Operations in SOR: -
Directly we are not able to modify any operations on SOR file. We use Object Repository Manager [ORM].
Brows and open required SOR Click open folder icon object Repository Manager Navigation: -Resource Menu
Click Save. on Objects perform required operations (Add, Rename, Delete) click Enable edit Icon file
Note: - if we do any modification in SOR file it changes in all associated object repositories.
Merging Shared Object Repository: - [we won‟t use]
Navigation: -Browse and Open select Object Repository Merge tool Tools select ORM Resources menu
save the file .tsr click save icon primary and secondary files
Types of Objects
With respect to OR we have 2 types of objects.
1. Test objects
2. Runtime Object
Test Object: -Objects which are in OR are called as test objects.
Runtime Objects: - objects which are in AUT are called as runtime objects.
Note: - Every Test object is a run time object.
Note: - Every runtime object may or may not be a test object
Working with Test Objects: -
1. GetToProperty()
2. GetToProperties()
3. SetToProperty()
GetToProperty (): -
It is used to retrieve test object given, property value during run time.
Syntax: -
Ex: - MsgBox dialog(“login”).WinButton(“Help”).GetTOProperty (“Text”) „Returns Help
MsgBox Dialog(“login”).GetToProperty(“text”)
Note: - 1. If given property is invalid or not available in Object Repository. It retrieves EMPTY.
2. Property names are not case sensitive
GetTOProperties(): -
It is used to retrieve multiple property names and its values for a test object, from OR during run time.
Ex: - MsgBox Dialog(“login”).GetTOProperties() „ Returns ERROR {Script 2 is an example for this}
Script No 2: - Write a script to retrieve property names and values per a login object
Set sPropertyLst = Dialog("Login").GetTOProperties
'MsgBox sPropertyLst.Count
For index = 0 To sPropertyLst.Count-1
Print sPropertyLst(index).Name & VbTab & sPropertyLst(index).Value
Next
Set sPropertyLst = Nothing
SetTOProperty(): -
It is used to change the test object property values during run time.
Whenever object properties are changing at runtime we use this method:
Syntax: -
Ex: - Dialog(“login”). SetTOProperty “text”,”sreekar”
Working with Run Time Objects: -
GetROProperty(): -
It used to retrieve run time object property value during run time
Syntax: -
Ex: - MsgBox Dialog(“login”).GetROProperty(“text”)
[Above code will retrieve QTP identified properties {in object spy}]
Note: -*** If we want to retrieve Native Properties for an object we use “Object()”
Syntax: -
[Native Properties are developers given properties {in object spy}]
Work Out: - Go through the button, text box, browser, page, link for Identified Properties and Native Properties
Adding objects to OR by Run Time
Types of Recording: -
1. Normal or Standard Recording
2. Analog Recording
3. Low-Level Recording
Normal or Standard: - It is used to record standard objects like Window, Web, VB, Java, Dot Net…Etc.
select desired environment (Web/ Windows) Record Button Navigation: - Open application (AUT)
observe that script is generated in click Stop perform operations on AUT Click OK Click Apply
test pane and respective objects added in OR.
Analog Recording: -
Analog recording is used to record diagrams, signatures, graphs…etc. It generates a single statement for
every start and stop recording.
Navigation:- Click Select Environment window or web Click Recording in QTP Open AUT
Select Record relative to the following window Select Analog Recording from Automation Menu OK
perform Click start analog record button with help of handler point select AUT radio button
Click Stop Recording in QTP. operation
Low-Level Recording: - It is used to record minimum operations on non-supported environments
Select Web/Windows Select desired Environment Click Record in QTP Navigation: -Open AUT
click STOP Recording. Perform operations on AUT Low Level Recording from Automation Menu
Object Repository Standards: -
1. What is an Object?
2. How QTP is recognizing objects?
3. What is OR?
4. What is your approach for writing a test script?
5. What is the default OR?
6. How do you add object to OR?
7. What is extension of PerAction of Local repository?
8. How do you create local Repository?
9. How many objects I can store in QTP test script?—2MB
10. How to create SOR?
11. What is difference between PerAction and SOR?
12. How many SOR files you have created for your project?
13. What is the file extension of SOR file?--.tsr
14. Where do you maintain all SOR files in your testing process?
15. Have you merged SOR files?
16. Why do you go for merging SOR files?
17. Can we do merge more than 2 SOR files at a time, if it is not then how do you merge more than two SOR
files?
18. How do you merge PerAction Repository?
19. How many objects are there and what are they?
20. How do you create test objects?
21. What are the methods you can find for Test Objects?
22. What is the difference between GetToProperty and GetToProperties method?
23. Write a test script for retrieving multiple properties and their values for a object?
24. How do you handle, if test object properties are dynamically changing during run time?
25. How do you retrieve object information during runtime?
26. What is the deference between GetToProperty and GetROProperty?
27. Which method you are using for retrieving object information GetToProperty or GetROProperty?
28. Who will create SOR?
29. How do you work with SOR?
QTP - Chapter V
Check Points
Check points are used to validate Object Properties, Comparing Text, Comparing Images, Validate Database…etc.
[OR] Check point is a verification point, it takes expected result from the user and compares with actual results
during execution and provides test results.
Types of Check Points: - There are 9 Checkpoints available in QTP:
1. Standard check point
2. Text check point
3. Text area check point
4. Bit map check point
5. Data base check point
6. Image checkpoint
7. Table checkpoint
8. XML Check point (from Application)
9. XML Check point (from Resource)
1. Standard Checkpoint: It is used to validate object properties
Navigation: -Open AUT Click Record in Qtp Insert Menu Check Point Select Standard Checkpoint
Select Expected properties and With help of handler Select Required Object Click on OK button
Values Click on OK Button.
Syntax: -
Ex: - Dialog (“Login”) .WinButton (“ok”). Check Checkpoint (“ok”)
Draw Backs of Check Checkpoint: -
All Checkpoint syntax is same and hence unable to find what kind of Checkpoint it is.
Copied checkpoint statement does not run in another script (Action)
And hence above are the reasons mostly we are not using any checkpoints, we convert checkpoints
scenarios in to VBScript
Converting check points to VBScript:
If Window (“Flight Reservation”).WinButton (“insert Order”).GetROProperty (“enabled”)=”true” Then
Window (“Flight Reservation”).WinButton (“insert Order”).Click
Else
MsgBox “Insert Order is disabled”
2. Text Checkpoint: -It is used to validate given text in given object
With Select Text Checkpoint Check Point Insert Menu Click Record in Qtp Navigation: - Open AUT
Select required Click on Configuration Button Click on OK button help of handler Select Required Objet
Stop Recording Click on OK Button text
Ex: -Window (“notepad”).WinEditor (“Edit”). Check Checkpoint (“Edit”)
Converting check points to VBScript:
In Notepad: - My name is Sreekar there is no prerequisite for learning QTP please come here and learn
QTP validate QTP is exist in notepad
sText = Window (“notepad”).WinEditor (“Edit”).GetROProperty (“Text”)
If InStr (sText, “qtp”) > 0 Then
MsgBox “Text is found”
Else
MsgBox “Text is Not Found”
3. Text Area Checkpoint: - It is used to validate given text is exist in between given text
Select Text Area Check Point Insert Menu Click Record in Qtp Navigation: - Open AUT
Stop Recording Click on OK Button Select Checked Text, Check After Text, Checked Before Text click on OK
Button Select Required Text Checkpoint
Ex: -Window (“notepad”).WinEditor (“Edit”). Check Checkpoint (“Edit”)
In Notepad: - My name is Sreekar there is no prerequisite for learning QTP please come here and learn QTP
validate QTP is exist in notepad
H.W:- Validate Sreekar is existing in Between name and QTP
4. Bitmap Checkpoint: -It is used to compare two images
Select Bit Map Check Point Insert Menu Click Record in Qtp Navigation: - Open AUT
Minimize or Close expected Stop Recording click on OK Button Select the Expected Image Checkpoint
Analyze the Result Run Script Open actual image[which need to Test] Image
Scripts related to Standard Checkpoint Check Points
Scripts related to Standard Checkpoint:
Script No3: - Write a script to validate Calculator Functionalities
Script No4: - Write a script for Object Existence [Validation of Vehicle Insurance]
Scripts related to Standard Checkpoint Check Points
How to get the Menu Options if we are not able to find with Obj Spy?
Script: - ********** Write a script to Select MENU Options
Method 1: - In Menu Options we cannot identify the objects with Object Spy through Recording we are
going to generate the script
Window ("Flight Reservation").Activate
Window ("Flight Reservation").WinMenu("Menu").Select "File;Open Order..."
Window ("Flight Reservation").WinMenu("Menu").Select "Help;About..."
Method 2: - Without Recording we get the Menu items by using short cut keys
Window ("Flight Reservation").Activate
Window ("Flight Reservation").Type micAltDwn + "h" + micAltUP + "a"
QTP - Chapter V
Scripts related to Standard Checkpoint Check Points
Script No12: - Write a Script to find given value is exist in DROP DOWN
Example: -kesinenitravels.com validate “HYDERABAD” is exist in from drop down
Method 1:-
Option Explicit
Dim sExpItem,iFlag,iItemCnt,index,sItemName,obj
sExpItem = "KURNOOL"
iFlag = 0
Set obj = Browser("Kesineni").Page("Kesineni")
iItemCnt = obj.WebList("From").GetROProperty("items count")
For index = 1 To iItemCnt
sItemName = obj.WebList("From").GetItem(index)
If sItemName = sExpItem Then
Print "Item is Found"
iFlag = 1
Exit for ' If we did not declare this the loop will iterate after getting the result also
End If
Next
If iFlag = 0 Then
print "Item Not Found" 'if we give it within for loop it iterates, so we took Flag for this
End If
Limitation: - Above Logic executes for all items if the items are at end or not found
Method 2:-
On Error Resume Next „It skips the Errors if any occurs in script running time
Set obj = Browser("Kesineni").Page("Kesineni")
obj.WebList("From").Select sExpItem
If Err.Number = 0 Then „Err.Number will give the script run time ERROR NUMBERS it is VB Utill
MsgBox "Item is found"
Else
MsgBox "Item Not Found"
End If
Limitation: -If item is not found then result window displays with RUNTIME ERROR which we won‟t
accept
Method 3:-
Question: - Write a script for dropdown
On Error Resume Next „It skips the Errors if any occurs in script running time
Set obj = Browser("Kesineni").Page("Kesineni")
sItemName = obj.WebList("From").GetROProperty("all items")
If InStr(sItemName, sExpItem) > 0 Then
MsgBox "Item is Found"
Else
MsgBox "Item Not Found"
End If
Question: - How do you find Combobox or ListBox items?
In Windows based application we have “GetItemCount”
In Web based application we have “GetROProperty (―item count‖)”
Note:-****
1. Err.Number: - To identify runtime error number
2. On Error Resume Next: - When we get any error in script execution it skips that line goes to next
Scripts related to Standard Checkpoint Check Points
Script No13: - Write a script for Rail Reservation
Set obj = Browser("Reservation").Pabe("Reservation")
obj.WebEdit("Name").Set "Sreekar"
obj.WebEdit("Age").Set "32"
obj.WebList("Gender").Select "Male"
obj.WebList("Name").Select "Hyderabad"
obj.WebList("Name").Select "Kurnool"
'Validate default Class
If obj.WebRadioGroup("Class").GetROProperty("value")
= "AC" Then
MsgBox "Default Class is AC"
Else
MsgBox "Default Class is Not AC"
End If
„Validate Class Price
obj.WebRadioGroup("Class").Select "AC"
iTcktPrice = obj.WebEdit ("Ticket Price").GetROProperty("text")
iTcktPrice = Mid(iTcktPrice,4,Len(iTcktPrice)-5) 'Rs:1000/-
If iTcktPrice = "1000" Then
MsgBox "AC Price is 1000/-"
Else
MsgBox "AC Price Not 1000/-"
End If
obj.WebRadioGroup("Class").Select "Sleeper"
iTcktPrice = obj.WebEdit ("Ticket Price").GetROProperty("text")
iTcktPrice = Mid(iTcktPrice,4,Len(iTcktPrice)-5) 'Rs:1000/-
If iTcktPrice = "1000" Then
MsgBox "Sleeper Price is 500/-"
Else
MsgBox "Sleeper Price Not 500/-"
End If
'Validate No of Tickets
iTickets = InputBox("Enter number of Tickets")
obj.WebEdit("Tickets").Set iTickets
obj.WeButton("Submit").Click
iTotalPrice = obj.WebEdit("Total Price").GetROProperty("text")
iTotalPrice = Mid(iTotalPrice,4,Len(iTotalPrice)-5)
If iTotalPrice = iTickets * iTicketPrice Then
MsgBox "Total Price Functionality Validation is Pass"
Else
MsgBox "Total Price Functionality Validation is Fail"
End If
iTcktNo = obj.WebEdit("TicketNo").GetProperty("text")
If NOT IsEmpty (iTcktNo) Then
MsgBox "Ticket Noumber Validation is Pass"
Else
MsgBox "Ticket Noumber Validation is Fail"
End If
Scripts Related to Text Checkpoint
Ex: - Notepad: - my name is sreekar there is no prerequisite for learning QTP please come here and learn QTP
Script No5: -Write a script to Validate Text Existence
Ex: - Notepad:
Validate sreekar text existence:-
Option Explicit
Dim sActTxt, sExpTxt
sExpTxt = "sreekar"
sActTxt =
Window("Notepad").WinEditor("Edit").GetROProperty
("text")
If InStr(sActTxt, sExpTxt) > 0Then
MsgBox "Text is Found"
Else
MsgBox "Text is Not Found"
End If
Script No6: -Write a script to find the string number of
occurrences
Ex: - Notepad:
Find sreekar text number of occurrence:-
Option Explicit
Dim sActTxt, sExpTxt
sExpTxt = "sreekar"
sActTxt =
Window("Notepad").WinEditor("Edit").GetROProperty
("text")
MsgBox (Len(sActTxt)-
Len(Replace(sActTxt,sExpTxt,"")))/ Len(sExpTxt)
Script No7: - Write a script to find the ovals
Ex: - Notepad: -
Option Explicit
Dim sActTxt, iACnt,iECnt,iICnt,iOCnt,iUCnt
sActTxt =
Window("Notepad").WinEditor("Edit").GetROProperty(
"text")
iACnt = Len(sActTxt)-Len(Replace(sActTxt,"a",""))
iECnt = Len(sActTxt)-Len(Replace(sActTxt,"e",""))
iICnt = Len(sActTxt)-Len(Replace(sActTxt,"i",""))
iOCnt = Len(sActTxt)-Len(Replace(sActTxt,"o",""))
iUCnt = Len(sActTxt)-Len(Replace(sActTxt,"u",""))
MsgBox iACnt+iECnt+iICnt+iOCnt+iUCnt
Script No8: - Write a script to find number of Alphabets
Ex: - Notepad: -
Option Explicit
Dim sActTxt,index,iCnt, iChrCnt
iChrCnt = 0
sActTxt = UCase(
Window("Notepad").WinEditor("Edit").GetROProperty(
"text"))
MsgBox Len(sActTxt)
For index = 65 To 90 'upper Case A - Z
iCnt = Len(sActTxt) - Len(Replace(sActTxt,
Chr(index),""))
iChrCnt=iChrCnt + iCnt
Next
MsgBox iChrCnt
Script No9: - Write a script to find number of strings in a given text [&_ for Continue the line]
Option Explicit
Dim sActTxt,index,iCnt, iChrCnt
sActTxt = "my name is sreekar there is no prerequisite for learning QTP"&_
"Please come here and learn QTP"
iChrCnt = 0
sActTxt = Split (sActTxt, " ")
MsgBox UBound (sActTxt) + 1
Scripts related to Text Area Checkpoint
Script No10: -Write a Script to find given text existence in between given two texts
Ex: - Notepad:Find sreekar in between name and QTP
Script No11: - Write a script to retrieve Driver letter, File Path and File Name from given Text
Option Explicit
Dim sActTxt,index,iCnt, iChrCnt
sActTxt = "D:sreekarbatch40test scriptssamplesample.mts"
MsgBox "Driver Letter is: - " & Mid(sActTxt,1,1)
MsgBox "File Name is: - " & Mid(sActTxt,InStrRev(sActTxt,"")+1)
MsgBox InStrRev(sActTxt,"")
MsgBox "File Path is: -" & Mid(sActTxt,4, InStrRev(sActTxt,"")-4)
[Here to find the file path we subtracted 4 {1st 3 {D :} letters and last occurrence of ―‖}]
CaptureBitMap: - It is used to take a screen for the given object
Syntax: - .CaptureBitMap “Path.bmp/png”
Ex: -
Capture Login
Dialog("Login").CaptureBitMap "E:01 My Scriptslogin.bmp"
Capture OK button in Login Dialog Dialog("Login").WinButton("OK").CaptureBitMap "E:01 My
Scriptsloginokbtn.bmp"
Note: - When we capture child object, QTP captures only child Object
Capture Desktop
Window ("text:= QuickTest.*").Minimize
Desktop.CaptureBitmap("E:01 My ScriptsDesktop.bmp")
Window("text=QuickTest.*").Maximize [;- Descriptive Programming]
Script No14: - Write a script to Right Click on Notepad editor and select past by using down arrow key
Set obj = CreateObject ("WScript.Shell")
Window("Notepad").Activate
iXCord = Window("Notepad").WinEditor("Edit").GetROProperty("x")
iYCord = Window("Notepad").WinEditor("Edit").GetROProperty("y")
Window("Notepad").Activate
Window("Notepad").WinEditor("Edit").Click iXCord, iYCord,micRightBtn
obj.SendKeys "{DOWN}" ' These things we can write in Loop
Wait(1)
obj.SendKeys "{DOWN}"
Wait(1)
obj.SendKeys "{DOWN}"
Wait(1)
obj.SendKeys "{DOWN}"
obj.SendKeys"{ENTER}"
For index= 1 To 4
obj.SendKeys "{DOWN}"
wait(1)
Next
Script No15: - Write a script to open an existing notepad right click on it, select ―Select All ―option by pressing/
Sending UP arrow key (in windows 7 it differs) one time, Right Click on Notepad, select copy option by sending
Down arrow key for 3 (in windows 7 it differs) times, close the notepad, open a new notepad, Right Click on it
select past by sending UP arrow key for 3(in windows 7 it differs) times.
SystemUtil.Run "E:01 My Scripts1.txt"
Set obj = CreateObject("WScript.Shell")
'Window("Notepad").Activate
iXCord = Window("Notepad").WinEditor("Edit").GetROProperty("x")
iYCord = Window("Notepad").WinEditor("Edit").GetROProperty("y")
'Window("Notepad").Activate
Window("Notepad").WinEditor("Edit").Click iXCord, iYCord,micRightBtn
For index = 1 To 6
obj.SendKeys"{UP}"
'Wait(1)
Next
obj.SendKeys"{ENTER}"
'Wait(1)
Window("Notepad").WinEditor("Edit").Click iXCord, iYCord,micRightBtn
For index1 = 1 To 3
obj.SendKeys"{DOWN}"
'Wait(1)
Next
obj.SendKeys"{ENTER}"
Window("Notepad").Close
SystemUtil.Run"Notepad"
Window("Notepad").WinEditor("Edit").Click iXCord,iYCord,micRightBtn
For index2 = 1 To 4
obj.SendKeys"{DOWN}"
'Wait(1)
Next
obj.SendKeys "{ENTER}"
Text Area Checkpoint - Desktop Check Points
Script No16: -Write a script to right click on Desktop, select Properties and validate “DESKTOP” Tab Existence in
“Display Properties Dialog” if exist then select it.
Option Explicit
Dim sExpTab,iFlag,sActTab,index,obj,iXCord,iYCord,iTabCnt
sExpTab = "Desktop"
iFlag = 0
Set obj = CreateObject("WScript.Shell")
iXCord = Window("Program Manager").WinListView("SysListView32").GetROProperty("x")
iYCord = Window("Program Manager").WinListView("SysListView32").GetROProperty("y")
Window("text:=QuickTest.*").Minimize
Window("Program Manager").WinListView("SysListView32").Click iXCord,iYCord,micRightBtn
Wait(1)
obj.SendKeys"{UP}"
obj.SendKeys"{ENTER}"
iTabCnt = Dialog("Display Properties").WinTab("SysTabControl32").GetItemsCount
For index = 0 To iTabCnt-1
sActTab = Dialog("Display Properties").WinTab("SysTabControl32").GetItem(index)
If sExpTab = sActTab Then
iFlag = 1
Dialog("Display Properties").WinTab("SysTabControl32").Select sExpTab
MsgBox "Given Tab is Found and Selected"
Exit For
End If
Next
If iFlag = 0 Then
MsgBox"Given Tab is Not Found"
End If
QTP - Chapter VI
Chapter VI
Working with Test Result
We display test results in Test Result window by using Reporter Utility Object
We display bellow Types of results:
1. Pass
2. Fail
3. Warning
4. Normal
Syntax: - Report.ReportEvent,””,””
We have 4 types of event status
1. micPass (0)
2. micFail (1)
3. micWarning (3)
4. micDone [Normal] (2)
Ex: - Reporter.Reportevent micPass, “Validate dialog login exist”,”Dialog login exist”
Reporter.Reportevent micFail, “Validate dialog login exist”,”Dialog login not exist”
Reporter.Reportevent micWarning, “Validate dialog login exist”,”Dialog login is minimized”
Reporter.Reportevent micDone, “execution start”, “Test script execution start”
Ex: - If Dialog (“login”).exist=”True” Then
Reporter.Reportevent micPass, “Validate dialog login exist”, “Dialog login exist”
Else
Reporter.Reportevent micFail, “Validate dialog login exist”, “Dialog login not exist”
Endif
Save text Results in Required Path: -
Navigation: - Click Run Button->Select new Run Results folder Radio button->Click Browser->Browse
and open required path->Click OK button.->After script execution QTP saved a given folder in given path.
QTP - Chapter VII - VIII - IX
Utility Objects
-->These are predefined by QTP which are used to enhancing scripting
Navigation: Insert Menu ->Step Generator -->Select Category as Utility Objects --> Find List of objects in Objects
Drop Down
Utility Objects: -
Navigation: - Insert Menu -->Stepgenerator -->Select Category as Utility Object -->Find List of Utility
Objects in object drop down
Crypt: - It encrypts the given script generally it is used to enter Secure Password
Eg: - Crypt.Encrypt (“mercury”) [:- object. method]
--> We can also encrypt the given string with bellow navigation
Start --> all programs -->QTP-->Tools -->Password Encoder-->Enter the String -->Click Generate Button-->click
Copy Button -->Paste it where needed.
Desktop: - It is used to work with desktop
***Note: -To click the radio button [Ex: - winRadioButton (“”).Set]
***Note: - To check the CheckBox we “ON”, “OFF” [Set “ON”/”OFF”]
To know whether CheckBox is checked are not go to spy check the Checked value as ON / OFF and assign
the value to GetROProperty
RandomNumber: - It is used to generate random number with given range
Example: -
1. Generate 4 digit random number
MsgBox RandomNumber (1000.9999)
2. Generate 5 Characters String
For index = 1 To 5
sStr = sStr & Chr(RandomNumber(65,90))
Next
MsgBox sStr
SystemUtil: - By using this we open and close application and its process during runtime
Run: -It is used to open application during runtime
Ex: - Open login Dialog
SystemUtil.Run "C:Program FilesHPQuickTest Professionalsamplesflightappflight4a.exe"
'Open internet explore
SystemUtil.Run "iexplore"
'Open internet explorer with URL
SystemUtil.Run "iexplore", "www.google.com"
'Open EXCEL
SystemUtil.Run "EXCEL"
'Open MS Word
SystemUtil.Run "WinWord"
CloseDescendentProcesses: - It closes all applications which are opened by QTP
Ex: -SystemUtil. CloseDescendentProcesses
CloseProcessByName: - It closes the given Process Name
Ex: -SystemUtil. CloseProcessByName ("EXCEL.EXE")
Synchronization
-->It is a process of matching the execution speeds for both application and QTP
We can implement Synchronization in 4 ways
1. Wait() function
2. WaitProperty Method
3. Increase/ Decrease default time Setting
4. VB Scripting **
1. Wait Function: --->By using this function we can make to QTP wait in given time in seconds
-->It‟s a static way
Limitations: - If given time is more than actual application time QTP still to wait, hence we have a
performance issue. If given time is less than actual application time than QTP does not wait and continues
to next step execution, hence we will get invalid results.
Syntax: - Wait (Time in Seconds)
Ex: - Wait (30)
2. WaitProperty Method: -
->By using this we can apply synchronization on required object. To wait QTP for given time in milliseconds.
Syntax: -
3. Increase/ Decrease default Time Setting: -
-->When ever QTP not able to perform any statement then it will wait up to given default time.
Navigation: - File -->Setting -->Run -->Increase/ Decrease default time in object Synchronization time out field in
seconds.
4. VB Script: - ***
Example: -
Obj. WinButton (“Insert Order”).Click
While obj. WinButton (―Update Order‖).GetROProperty (―enabled‖) = ―False‖
Wend
iOrdNo = obj.WinEdit (“Order No”). GetROProperty (“text”)
MsgBox iOrdNo
[To know the execution time of use MercuryTimers in Utility Objects]
Example: -For Synchronization {for this we need Flight Reservation Application}
Chapter IX
Parameterization
Parameterization: - It is a process of replacing static values with dynamic values and executing test
scripts with multiple test data is called as parameterization.
--> We maintain test data and passing it to UT through QTP in bellow ways.
1. Data Table
2. Environment Variable
3. External Files [Ms-Excel, Notepad, Ms-Word, XML]
4. Action Parameters
QTP - Chapter X - XI
Data Table Parametrization
Chapter X
Implementing parametrization by using Data Table
Data Table: - It is used to hold the Test Date
Navigation: - Data Table View Menu
--> It is looks like MS-Excel Spread Sheet
--> It contains 65536 Rows and 256 Columns
--> By default it contains Global and Action1 Sheet
--> Every action of the scripts contains the same sheet in the Data Table
Types of Data Table: -
1. Design Data Table
2. Run Time Data Table
Design Data Table: - Table which is displaying in test pane is called as Design Data Table
Run Time Data Table: - The table which is displaying result window called as Runtime Data Table
Note: - Run time Data Table is copy of Design Data Table
Note: - Any modifications to data table during runtime it performs the operations in Run Time Data Table
not in Design Data Table
Note: -Test script execution iterations depends on Global Sheet number of Rows
Example: -
Global Action1 Action No. of Iterations
- - - 1
- 5 10 1
5 10 15 5
10 5 1 10
Rename the column Names of Data Table: -
Navigation: - Select the required sheet Design Data Table -->Double click on required column -->Enter
new column name -->Click OK Button.
By Scripting: -
Syntax: - DataTable.GetSheet (“”).AddParameter””, “”
Example: - Adding User_Name Column in Global Sheet
DataTable.GetSheet(“Global”).AddParameter”User_Name”,”Sreekar”
Example: - Adding Val1 Column in Action1 Sheet
DataTable.GetSheet(“Action1”).AddParameter”Val1”,”Sreekar”
ScriptNo17: - Write a script to find given sheet existence in data table
sExpSht = "Action"
iFlag = 0
iShtCnt = DataTable.GetSheetCount
'MsgBox iShtCnt
For index = 1 To iShtCnt
sActSht = DataTable.GetSheet(index).Name
If sExpSht = sActSht Then
Print "Sheet is Found"
iFlag = 1
Exit For
End If
Next
If iFlag = 0 Then
Print "Sheet is not Found"
End If
Retrieving data From Data Table: -
--> It retrieves from Run Time Data Table not from Design Table
1. MsgBox DataTable("User_Name")
MsgBox DataTable("User_Name",1)
MsgBox DataTable("User_Name","Global")
MsgBox DataTable. Value("User_Name",1)
-->It retrieves User_Name Column value from Global Sheet
2. MsgBox DataTable("User_Name","Action1")
-->It retries User_Name Column Value from Action1 Sheet
3. MsgBox DataTable.GetSheet("Global").GetParameter("User_Name").ValueByRow(4)
-->It retrieves 4th of User_Name column value from Global Sheet
4. MsgBox DataTable.GetSheet("Action1").GetParameter("User_Name").ValueByRow(4)
-->It retrieves 4th row of User_Name column value from Action1 Sheet
Entering Data into Data Table: -
1. DataTable("val","Global")="QTP"
It Enters "QTP" in val column of Global Sheet
2. DataTable("val","Action1")="QTP"
It Enters "QTP" in val column of Action1 Sheet
3. DataTable.GetSheet("Global").GetParameter("val").ValueByRow(3)="QTP"
It Enters "QTP" in 3rd Row of val column in Global Sheet
4. DataTable.GetSheet("Action1").GetParameter("val").ValueByRow(3)="QTP"
It Enters "QTP" in 3rd Row of val column in Action1Sheet
Methods for Data Table: -By using this method we can perform required operations to the Run Time
Data Table
1. AddSheet: - It is used to add a required sheet to the Run time Data Table (RDT)
Syntax: - DataTable. AddSheet””
Ex: - DataTable.AddSheet"MySheet"
-->If we have data in multiple rows in Global Sheet then it over rights the sheet do not creates
new sheet like MYSheet1
2. DeleteSheet: - It is used to Delete a required sheet from RDT
Syntax: - DataTable. DeleteSheet""
Ex: DataTable.DeleteSheet"Global"
DataTable.AddSheet"MySheet"
DataTable.DeleteSheet"Action1"
-->At least one is default in Data Table
3. Export: - It is used to save a RDT in given path
Syntax: - DataTable.Export”Path”
Ex: - DataTable.Export"E:01 My Scriptstest.xls"
4. ExportSheet: - It is used to Save a required sheet of RDT in required path
Syntax: - DataTable.ExportSheet"Path",””
Ex: DataTable.AddSheet"MySheet"
DataTable.GetSheet("MySheet").AddParameter"User_Name","Sreekar"
DataTable.ExportSheet"E:01 My Scriptstest.xls","MySheet"
5. GetCurrentRow: - It is used to retrieve the current Active Row from the required sheet of
RDT.
Ex: - --> Retrieving from Global Sheet
MsgBox DataTable.GetCurrentRow (or)
MsgBox DataTable.GetSheet("Global").GetCurrentRow
Retrieving from Action1 Sheet
MsgBox DataTable.GetSheet("Action1").GetCurrentRow
6. GetRowCount: - By using this we can retrieve number of rows from required sheet of RDT
Ex: -->Retrieving from Global Sheet
MsgBox DataTable.GetRowCount (or)
MsgBox DataTable.GetSheet("Global").GetRowCount
-->Retrieving from Action1 Sheet
MsgBox DataTable.GetSheet("Action1").GetRowCount
7. GetSheet: - It is used to Activate required sheet from RDT
Syntax: - DataTable.GetSheet("")
Example: -DataTable.GetSheet("Global")
DataTable.GetSheet("Action1")
8. GetSheetCount: - It is used to retrieve number of sheets from RDT
Ex: - MsgBox DataTable.GetSheetCount
9. Import: - It is used to save a excel file in RDT [How many sheets we have in RDT it imports
only that number of sheets from Excel]
Ex: - DataTable.AddSheet"MySheet"
DataTable.Import"E:01 My Scriptstest.xls"
10. ImportSheet: - It is used to save a required sheet of MS-Excel to required sheet of RDT
Syntax: - DataTable.ImportSheet”Path”,Ms-Excle Sheet ID, RDT Sheet ID
Ex: - DataTable.ImportSheet"E:01 My Scriptstest.xls",3,2
11. SetCurrentRow: - It is used to activate required row in required sheet of RDT
Ex: - -->Activating row in Global Sheet
DataTable.SetCurrentRow(1) [or]
DataTable.GetSheet ("Global").SetCurrentRow(2)
-->Activating row in Action1Sheet
DataTable.GetSheet ("Action1").SetCurrentRow(2)
12. SetNextRow: - It activates the Next row of current active row
Ex: ---> Activating Global Sheet
DataTable. SetNextRow (or)
DataTable.GetSheet("Global").SetNextRow
-->Activating Action1 Sheet
DataTable.GetSheet("Action1").SetNextRow
13. SetPrevRow: -It activates previous row of current active row
Ex: - -->Activating Global Sheet
DataTable. SetPrevRow
DataTable.GetSheet("Global").SetPrevRow
-->Activating Action1 Sheet
DataTable.GetSheet("Action1").SetPrevRow
Ex: - MsgBox DataTable. GetCurrentRow
DataTable.GetSheet ("Action1").SetPrevRow
DataTable ("val1","Action1")
ScriptNo18: - Write a script to find mathematical operation to given values, maintain data in Excel File.
On Error Resume Next
Dim iRowCnt,iRowNum,iVal1,iVal2
DataTable.ImportSheet"E:01 My Scriptscal.xls", 1, 2
iRowCnt = DataTable.GetSheet("Action1").GetRowCount
For iRowNum = 1 To iRowCnt
iVal1 = CInt (DataTable("val1","Action1"))
iVal2 = CInt (DataTable("val2","Action1"))
DataTable("add","Action1") = iVal1 + iVal2
DataTable("sub","Action1") = iVal1 - iVal2
DataTable("mul","Action1") = iVal1 * iVal2
DataTable("div","Action1") = iVal1 / iVal2
If Err.Number <> 0 Then
DataTable("comments","Action1") = Err.Description
Err.Clear
End If
DataTable.GetSheet("Action1").SetNextRow
Next
DataTable.Export"E:01 My Scriptscalresult.xls"
ScriptNo19: - Write a script for Login functionality for Multiple Users -->Maintain DATA in MS-Excel
DataTable.ImportSheet"E:01 My Scriptsdatatable-user.xls",1,2
iRowCnt = DataTable.GetSheet("Action1").GetRowCount
For i = 1 To iRowCnt
sUname = DataTable("Username","Action1")
sPwd = DataTable("Password","Action1")
SystemUtil.Run "C:Program FilesHPQuickTest Professionalsamplesflightappflight4a.exe"
If Dialog("Login").Exist Then
Dialog("Login").Activate
Dialog("Login").WinEdit("Agent Name:").Set sUname
Dialog("Login").WinEdit("Password:").Set sPwd
Dialog("Login").WinButton("OK").Click
If Dialog("Login").Dialog("Flight Reservations").Exist(5) Then
Dialog("Login").Dialog("Flight Reservations").Activate
sError = Dialog("Login").Dialog("Flight Reservations").Static("Please enter agent
name").GetROProperty("text")
Dialog("Login").Dialog("Flight Reservations").Close
Dialog("Login").Close
DataTable("Results","Action1") = sError
Else
If Window("Flight Reservation").Exist Then
DataTable("Results","Action1") = "Valid User"
Window("Flight Reservation").Activate
Window("Flight Reservation").Close
Else
DataTable("Results","Action1") = "User is valid but not opened the application"
End If
End If
Else
DataTable("Results","Action1") = "Application not Oppened"
End If
DataTable.GetSheet("Action1").SetNextRow
Next
DataTable.Export"E:01 My Scriptsdatatable-user1.xls"
ScriptNo20: - Write a script to retrieve Fly From dropdown values [Maintain in Excel]
ScriptNo21: - Write a script to import Val1 values from sample1.xls file and import Val2 values from sample2.xls
file, perform the mathematical operations and write the result in results.xls file
QTP - Chapter XI
Parameterization
Environment Variable
Implementing parameterization by using Environment Variable
By using Environment Variables we can share the variable values in multiple actions (or) multiple scripts
Types of Environment Variables: -
1. Built-In Environment Variables
2. User Defined Internal Environment Variables
3. User Defined External Environment Variables
Built-In: - These are Pre-Defined by QTP
Navigation: - Select Variable Type as Built-In Environment Setting File Menu
Ex: - ActionName: Retrieves current action name
ResultDir: Retrieves Test Script execution Result Path
TestName: Retrieves Current Test Script Name
MsgBox Environment ("ActionName")
MsgBox Environment ("ResultDir")
MsgBox Environment ("TestName")
Note 1: - Built-In Environment variables are Read-Only
Note 2: - Environment Variables are case sensitive
User Defined Internal: -
Declaring and using in same test scripts are called as User Defined Internal Environment Variables
Navigation: - File Menu-->Environment Setting-->Select Variable Type as User Defined-->Click on ADD[+]
Button Enter name and Value-->Click OK button -->Click Apply and OK
Note: - Internal Environment variables are not Read-Only we can modify data at run time.
Syntax: - Environment(“”) = “”
Environment(“iVal”) = 10
User Defined External: -
Creating external Environment Variables: -
Method 1: By Navigation: -
File Menu-->Setting-->Environment-->Select Variable Type as User Defined-->Click on ADD [+] Button Enter
Name
and Value-->click on OK button-->click Export Button-->Save the file in required path with “.XML”
extension
Method 2: Open NOTEPAD and declare the variables as follows
sPassword
mercury
sUserName
suresh
Associating External Environment Variable File:-
Method 1: Navigation: -
File Menu-->Setting-->Environment-->Select Variable Type as User Defined-->Click on Load Variables and Values
from Eternal File Check Box-->Browse XML file-->Click Apply and OK buttons
Method 2: -
Syntax: - Environment.LoadFromFile”File Path”
Environment.LoadFromFile "E:01 My Scriptsexternal EV.xml"
Note: - We can associate only one XML file by navigation OR by scripting if we associate 2nd file then first file will
be replaced with second file.
Note: - User Defined External Environment Variable are Read Only..
QTP - Chapter XII
External File [Excel] Parameterization
Implementing parameterization by using External File
External files are the files where we maintain the data outside of QTP, like ms-Excel, Notepad, Ms-Word, XML…
Working with MS-EXCEL
Creating Excel Object: - Set objXL = CreateObject("Excel.Application")
Creating Work Book Object: - Set objWrkBk = objXL.Workbooks.Add
Open an Existing Work Book: - Set objWrkBk = objXL.Workbooks.Open("E:01 My Scriptsexternal EV.xml")
Creating a Work Sheet Object: - Set objWrkSht = objWrkBk.Worksheets("Sheet1") 'Activating the Sheet
Find the No. of Rows: -
MsgBox objWrkSht.UsedRange.Rows.Count
Find the No. of Columns:-
MsgBox objWrkSht.UsedRange.Columns.Count
Retrieving a required Cell Value: - MsgBox objWrkSht.Cell(3,2)
Entering data to Cell: - objWrkSht.Cell(14,8) = "QTP"
Save opened Work Book: - objWrkBk.Save
Save the New Work Book: - objWrkBk.SaveAs"Path"
Close the Work Book: - objWrkBk.Close
Close Excel: - objXL.Quit
Kill Excel Process: - Set objWrkSht = Nothing
Set objWrkBk = Nothing
Set objXL = Nothing
External File [Excel]
ScriptNo22: - Write a script to create orders maintain data in Excel file
'Option Explicit
'Dim objXL,objWrkBk,objWrkSht,iRowCnt
Set objXL = CreateObject("Excel.Application")
Set objWrkBk = objXL.Workbooks.Open("E:01 My ScriptsExcel.xls")
Set objWrkSht = objWrkBk.Worksheets("Sheet1")
iRowCnt = objWrkSht.UsedRange.Rows.Count
Set obj = Window("Flight Reservation")
For index = 2 To iRowCnt
obj.Activate
obj.WinMenu("Menu").Select "File;New Order"
dDate = objWrkSht.Cells(index,1) '(Row,Column)
obj.WinObject("Date of Flight:").Type dDate
sFrom = objWrkSht.Cells(index,2)
obj.WinComboBox("Fly From:").Select sFrom
sTo = objWrkSht.Cells(index,3)
obj.WinComboBox("Fly To:").Select sTo
obj.WinButton("FLIGHT").Click
obj.Dialog("Flights Table").WinList("From").Select(0)
obj.Dialog("Flights Table").WinButton("OK").Click
sName = objWrkSht.Cells(index,4)
obj.WinEdit("Name:").Set sName
sCls = objWrkSht.Cells(index,5)
obj.WinRadioButton(sCls).Set
iTckts = objWrkSht.Cells(index,6)
obj.WinEdit("Tickets:").Set iTckts
obj.WinButton("Insert Order").Click
While obj.WinButton("Update Order").GetROProperty("Enabled") = "False"
Wend
iOrdNo = obj.WinEdit("Order No:").GetROProperty("Text")
If IsEmpty(iOrdNo) = "False" Then
objWrkSht.Cells(index,7) = obj.WinEdit("Price:").GetROProperty("Text")
objWrkSht.Cells(index,8) = obj.WinEdit("Total:").GetROProperty("Text")
objWrkSht.Cells(index,9) = obj.WinEdit("Order No:").GetROProperty("Text")
objWrkSht.Cells(index,10) = "Order is Generated"
Else
objWrkSht.Cells(index,10) = "Order is Not Generated"
End If
Next
objWrkBk.Save
objWrkBk.Close
objXL.Quit
Set objWrkSht = Nothing
Set objWrkBk = Nothing
Set objXL = Nothing
Renaming a Sheet Name: -
Set objXL = CreateObject ("Excel.Application")
Set objWrkBk = objXL.Workbooks.Open("E:01 My ScriptsExcel1.xlsx")
Set objWrkSht = objWrkBk.Worksheets("Sheet2")
objWrkSht.Name = "User_Data1"
Add a New sheet to Workbook: -
objWrkBk.Sheets.Add
Delete an Existence Sheet: -
objWrkBk.Sheets("Sheet3").Select
objXL.ActiveWindow.SelectedSheets.Delete
Auto fit for require Column in Active Sheet: -
objWrkSht.Columns("D:D").EntireColumn.AutoFit
Wrap Text {Format Column}: -
'objWrkSht.Columns("A1:D1").HorizontalAlignment = xlGeneral
'objWrkSht.Columns("A1:D1").VerticalAlignment = xlTop
objWrkSht.Columns("A1:D1").WrapText = True
Bold and Color to one Cell: -
objWrkSht.Cells(8,8).Font.Bold = True
objWrkSht.Cells(8,8).Font.Color = vbRed
objWrkSht.Cells(8,8) = "Suresh"
objWrkSht.Cells(8,8).Interior.ColorIndex = 55
ScriptNo23: - Write a script to retrieve val1 values from sheet1, retrieve val2 values from sheet2 and perform
mathematical operation and retrieve the results in sheet3
Working with NOTEPAD
Creating notepad Object: -
Set objFile = CreateObject ("Scripting.FileSystemObject")
Creating Notepad Pointer: -
Syntax: -Set objPtr = objFile. OpenTextFile (“Path of Notepad”,Mode[,True])
Set objPtr = objFile. OpenTextFile ("E:01 My Scripts1.txt",1)
Retrieving Value from notepad: -
Retrieving a Line: objPtr.ReadLine
Retrieving all Values: objPtr.ReadAll
Retrieving One by One on till end of Line:
While objPtr.AtEndOfLine = "False"
MsgBox objPtr.SkipLine 'Even
MsgBox objPtr.ReadLine
MsgBox objPtr.SkipLine 'Odd
Wend
Retrieving given Line value: -
Set objFile = CreateObject ("Scripting.FileSystemObject")
Set objPtr = objFile. OpenTextFile ("E:01 My Scripts1.txt",1)
iLine = 1
iFlag = 0
While objPtr.AtEndOfLine = "False"
If iLine = 5 Then
MsgBox objPtr.ReadLine
iFlag = 1
Else
ival1 = objPtr.ReadLine
End If
iLine = iLine + 1
Wend
If iFlag= 0 Then
MsgBox "Line number not found" End If
Entering the Data/values into notepad: -
Set objFile = CreateObject("Scripting.fileSystemObject")
Set objPtr = objFile.OpenTextFile("E:01 My Scripts2.txt",2,True )
objPtr.write "Suresh"
objPtr.WriteLine "Sreekar"
objPtr.WriteLine"Prsad"
objPtr.WriteLine "Srilatha"
objPtr.Write "Sushma"
objPtr.WriteLine"Subashini"
objPtr.Write"Sandeep"
objPtr.Write"Sanjay"
Notepad Object Method: -
1. CopyFile
2. CopyFolder
3. CreateFolder
4. CreateTextFile
5. DeleteFile
6. DeleteFolder
7. FileExists
8. FolderExists
9. OpenTextFile
CopyFile: - Copy one file content to another file of same file types
Syntax: - objFile.CopyFile"path of source file","path of destination file"
Ex: - objFile.CopyFile" D:sample1.txt ","D: sample2.txt"
CopyFolder: - Copy one file content to another file of same file types
Syntax: - objFile.CopyFolder"path of source file","path of destination file"
CreateFolder: - It is used to create a required folder in required path
Syntax: -objFile.CreateFolder”path”
Ex: - objFile.CreateFolder”d:test datasample”
Creating a Folder with Current System data & time:
Set objFile = CreateObject("Scripting.FileSystemObject")
iFoldername = Now
iFoldername = Replace(iFoldername,"/","_")
iFoldername = Replace(iFoldername,":","_")
objFile.CreateFolder "E:01 My Scripts"&iFoldername
CreateTextFile: - By using this method we can create new Notepad File
Ex: - Set objFile = CreateObject("Scripting.fileSystemObject")
objFile.CreateTextFile("E:01 My ScriptsSample3.txt")
DeleteFile: - Used to delete existing file
DeleteFolder: - Used to delete existing Folder
FileExists: - By using this method we can find file exist:
It returns True if file exist
It returns False if file exist
Ex: - MsgBox objFile.FileExists("E:01 My ScriptsSample3.txt")
FolderExists: - By using this method we can find Folder exist:
It returns True if file exist
It returns False if file exist
Ex: - MsgBox objFile.FolderExists("E:01 My Scripts")
OpenTextFile: - It is used to open exist text file for read/write/ append
Ex: - Set objPtr = objFile.OpenTextFile("E:01 My Scripts2.txt",2)
ScriptNo24: - Write a script to copy sample excel data into Notepad
Set objFile = CreateObject("Scripting.fileSystemObject")
Set objPtr = objFile.OpenTextFile("E:01 My Scripts3.txt",2,True)
Set objXl = CreateObject("Excel.Application")
Set objWrkBk = objXl.Workbooks.Open("E:01 My ScriptsExp.xlsx")
Set objWrkSht = objWrkBk.Worksheets("Sheet1")
iRowCnt = objWrkSht.UsedRange.Rows.Count
For iRowNum = 2 To iRowCnt
sName = objWrkSht.Cells(iRowNum,1)
iExperience = objWrkSht.Cells(iRowNum,2)
sIndustry = objWrkSht.Cells(iRowNum,3)
objPtr.WriteLine sName&" has "&iExperience&" Years of Experience in "&sIndustry&" industry”
Next
objWrkBk.Close
Set objWrkSht = Nothing
Set objWrkBk = Nothing
Set objXl = Nothing
Set objPtr = Nothing
Set objFile = Nothing
ScriptNo25: - Write a script for Fax Order; maintain fax numbers in notepad file
Set objFile = CreateObject("Scripting.FileSystemObject")
Set objPtr1 = objFile.OpenTextFile("E:01 My Scripts2.txt",1)
Set objPtr2 = objFile.OpenTextFile("E:01 My Scripts4.txt",2,True)
Set obj = Window("Flight Reservation")
While objPtr1.AtEndOfLine = "False"
sStr = objPtr1.ReadLine
sString = Split(sStr," ")
iOrderNo = sString(3)
iFaxNo = sString(8)
'MsgBox iOrderNo &" " &iFaxNo
obj.Activate
obj.WinMenu("Menu").Select "File;Open Order..."
obj.Dialog("Open Order").WinCheckBox("Order No.").Set "ON"
obj.Dialog("Open Order").WinEdit("Edit_2").Set iOrderNo
obj.Dialog("Open Order").WinButton("OK").Click
If obj.Dialog("Open Order").Dialog("Flight Reservations").Exist(4) Then
obj.Dialog("Open Order").Dialog("Flight Reservations").WinButton("OK").Click
obj.Dialog("Open Order").WinButton("Cancel").Click
objPtr2.WriteLine iOrderNo &"Order is not found and hence unable to send Fax"
Else
obj.Activate
obj.WinMenu("Menu").Select "File;Fax Order..."
obj.Dialog("Fax Order No. 1").WinObject("Fax Number:").Type iFaxNo
obj.Window("Fax Order No. 1").RunAnalog "Track1"
obj.Dialog("Fax Order No. 1").WinButton("Send").Click
If obj.Dialog("Fax Order No. 1").Dialog("Flight Reservations").Exist(4) Then
obj.Dialog("Fax Order No. 1").Dialog("Flight Reservations").WinButton("OK").Click
obj.Dialog("Fax Order No. 1").WinButton("Cancel").Click
objPtr2.WriteLine "Invalid Fax Number" &iFaxNo& "For the Order" &iOrderNo
Else
While obj.Dialog("Fax Order No. 1").Exist(2) = True
Wend
sFaxMsg = obj.WinObject("Fax Sent Successfully...").GetROProperty("Text")
If sFaxMsg = "Fax Sent Successfully..." Then
objPtr2.WriteLine "Fax Sent Success Fully for the order " &iOrderNo
Else
objPtr2.WriteLine "Fax Sent Success Fully for the order " &iOrderNo
End If
End If
End If
Wend
Note: - Generally we use Notepad for maintaining DATABASE queries
Note: - For general maintaining data like UserName, Password…etc we use excel files
Working with Ms-Word
Set objWrd = CreateObject(“Word.Application”)
Creating XML object
Set objXML = CreateObject(“XML.Application”)
Implementing parameterization by using Action Parameters
-->Actions are used to divide test script in to logically related groups of QTP statements.
-->Actions are used to script maintainability and script re-usability.
--> We use actions when functional testers maintain scenario based test scripts. That is one scenario containing
multiple test cases.
Ex: - Scenario
-->Every script we have “default action”, it is Action1
-->Every action of script will have sheet in data table and sheet name will be same as Action name.
Creating a New Action: -
Method-1:-
By Navigation: - Click OK Button Enter Action Name Call to New Action Insert Menu
Method-2:-
Run Time: - Set objQtp = CreateObject(“QuickTest.Application”)
objQtp.Test.AddNewAction””,””,”
Content>”,””,””
Ex: - objQtp.Test.AddNewAction “sample”,”test”,”test”, 1, 1
ScriptNo26: - Write a script to create multiple Actions and prove that we can create only 255 actions
QTP - Chapter XIII
Re-Naming: - Select the required Action-->Right Click on Test Pane-->Actions-->Action Properties-->Re-Name the
Action Name-->Click OK button.
Deleting an Action: -
Navigation1: -Select the required action-->Edit Menu-->Action-->Delete Action-->Click Yes Button in
Conformation
message.
Navigation2: - Keyword view -->Right Click on required Action-->Select Delete-->Click Yes Button in
conformation
message.
ScriptNo27: - Write a script to find given Action Existence
sExpAction = "Action5"
iFlag = 0
Set objQtp = CreateObject("QuickTest.Application")
iActionCnt = objQtp.Test.Actions.Count
MsgBox iActionCnt
For index = 1 to iActionCnt
Print objQtp.Test.Actions(index).Name
If objQtp.Test.Actions (index).Name = sExpAction Then
MsgBox "Action is Found"
iFlag = 1
Exit for
End If
Next
If iFlag = 0 Then
MsgBox "Action is Not Found"
End If
Set objQtp = Nothing
-->By default actions are executing in order which we are created.
-->If we want to change the order of action execution then we follow bellow navigation
Navigation: - Select the required action and drag and drop in required position Keyword View
Types of Actions: -
1. Normal /Non Reusable Action
2. Re- Usable Actions
3. External Re-Usable Actions
Normal /Non Reusable Action: - An Action that can be called only in the test without reusability called as Normal
/Non Reusable Action.
Re- Usable Actions: - An Action that can be called in same test script and in another test script multiple times is
called as Re- Usable Actions.
External Re-Usable Actions: - An Action that can be call in same test script or in another test script in multiple
times in READ ONLY mode are called as External Re-Usable Actions
Implement Script Reusability by Action: -
We can implement a Script Reusability by Action, in bellow ways
1. Call to Copy of Action
2. Call to Existing Action
Calling Action: - The Action which is calling another action
Called Action: - The Action which is called by another Action
Implementing re usability by using Call to Copy: -
Navigation: - Open calling test script -->insert Menu --> select call to copy of action -->browse the required called
to
test script -->select the required action --> click on OK button
Syntax: - RunAction”Copy of ”, OneIteration
Ex: - RunAction “Copy of login”, OneIteration
RunAction “Copy of logout”, OneIteration
Implementing re usability by using Call to Existing: -
Navigation: - Open calling test script --> nsert Menu --> select call to Existing action-->browse the required called
test
script-->select the required action --> click on OK button
Syntax: - RunAction “[Called Test Script]”, OneIteration
Ex: - RunAction “login[Action Demo]”, OneIteration
RunAction “logout[Action Demo]”, OneIteration
Difference between call to Copy and Call to Existing: -
Implementing Parameterization by using Action Parameters
Action Parameters: - These are used to retrieving the data and sending results in between Called Action and
Calling Action parameters.
There are two types of action parameters
1. Input Parameters: - These are used to retrieving the data from Calling Action to Called Action
2. Output Parameters: - These are used to sending Test Result from Called Action to Calling Action
Note: - We create Action Parameters in Called Action.
Note: - Action Parameters are independent to Action
Navigation to create Action Parameters: -
Open Called test script-->select the required action right click on test pane-->select Action-->Action
Properties-->select Parameter Tab-->Click Add button-->Enter parameter name and value-->Click on OK button.
Split of Action: - Right click on required statement-->select Action-->Split-->Enter First Action Name--> Enter
Second Action Name-->Click on OK button
ScriptNo28: - Write a script for login logout by using Action Parameter Concept
-->Open called Test Script and create 2 actions login and logout
-->Enter bellow code
-->Create sUname, sPwd input parameters and sRslt as output parameters
Script Name [loginlogout]-Action Name [Login]: -
[Add Action Parameters (sUName, sPwd, sRslt) to loginlogout script]
SystemUtil.Run "C:Program FilesHPQuickTest Professionalsamplesflightappflight4a.exe"
If Dialog("Login").Exist Then
Dialog("Login").Activate
Dialog("Login").WinEdit("Agent Name:").Set Parameter("sUName")
Wait(2)
Dialog("Login").WinEdit("Password:").Set Parameter("sPwd")
Dialog("Login").WinButton("OK").Click
If Dialog("Login").Dialog("Flight Reservations").Exist(5) Then
Reporter.ReportEvent micFail,"Login Validation","Given Data is Invalid"
Parameter("sRslt") = "Fail"
Dialog("Login").Dialog("Flight Reservations").WinButton("OK").Click
Dialog("Login").WinButton("Cancel").Click
Else
If Window("Flight Reservation").Exist Then
Reporter.ReportEvent micPass, "Login Validation","Login Validation is Pass"
Parameter("sRslt") = "Pass"
Window("Flight Reservation").Close
Else
Reporter.ReportEvent micFail, "Login Validation","Login Validation is Fail"
Parameter("sRslt") = "Fail"
End If
End If
End If
Action Name [Logout]: -
If Window("Flight Reservation").Exist(5) Then
Window("Flight Reservation").Close
While Window("Flight Reservation").Exist(2) = True
Wend
If Window("Flight Reservation").Exist(2) = "False" Then
Reporter.ReportEvent micPass, "Close Application","Application is Closed"
Else
Reporter.ReportEvent micFail,"Close Application","Application is not Closed"
End If
End If
[Here loginlogout script is called actions]
Script Name [calngaction]: - this action is calling action
Action Template: -
It explains Action description as bellow
*********************************************************************************
ACtion name:
Action Description:
Design Date:
Tool Used:
Comments:
*********************************************************************************
Navigation: - Open notepad enter the action template save the file as “ActionTemplate.mst” [MST: -mercury
scenario test script] in bellow path save it C:Program filesHPQuick Test Professionaldat
Split of Action: - Right click on required statement-->select Action-->Enter First Action Name Split--> Enter
Second Action Name-->Click on OK button
ScriptNo29: -HW
ActionDemo: - Action1
'MsgBox "Login"
SystemUtil.Run "C:Program Files (x86)HPQuickTest Professionalsamplesflightappflight4a.exe"
If Dialog("Login").Exist Then
Dialog("Login").Activate
'Msgbox Parameter("suname")
'MsgBox Parameter("spwd")
Dialog("Login").WinEdit("Agent Name:").Set parameter("suname")
Dialog("Login").WinEdit("Password:").Set Parameter("spwd")
Dialog("Login").WinButton("OK").Click
If Dialog("Login").Dialog("Flight Reservations").Exist(3) Then
Reporter.ReportEvent micFail, "Login Validation", "Invalid credentials "
Parameter("srslt") = "Fail"
Dialog("Login").Dialog("Flight Reservations").WinButton("OK").Click
Dialog("Login").WinButton("Cancel").Click
Else
Reporter.ReportEvent micPass , "Login Validation", "succesfully logged into flight reservation"
Parameter("srslt") = "Pass"
End If
Else
Reporter.ReportEvent micFail, "Login Validation", "Flight application is not opened"
Parameter("srslt") = "Fail"
End If
Action2: -
If Window("Flight Reservation").Exist Then
Window("Flight Reservation").Close
While Window("Flight Reservation").Exist(2) = True
Wend
If Window("Flight Reservation").Exist(3) = "False" Then
Reporter.ReportEvent micPass, "Close Application", "Application is closed"
Else
Reporter.ReportEvent micFail,"close application","app is not closed"
End If
Else
Reporter.ReportEvent micFail,"close app","app is not closed"
End If
New Order: -
Open Order: -
Fax Order: -
'Msgbox "Fax Order"
Set objxl=CreateObject("Excel.Application")
Set objwbk=objxl.Workbooks.Open ("D:Projectfaxorder.xls")
Set objwst = objwbk.Worksheets("sheet1")
Set objFile = CreateObject("Scripting.FileSystemObject")
Set objptr = objFile.OpenTextFile("D:ProjectFlightDetails.txt",8)
iRcnt=objwst.UsedRange.Rows.count
Set obj= window("Flight Reservation")
If obj.Exist (5) Then
For indx = 2 to iRcnt
obj.Activate
obj.WinMenu("Menu").Select "File;Open Order..."
obj.Dialog("Open Order").WinCheckBox("Order No.").Set "ON"
obj.Dialog("Open Order").WinEdit("Edit_2").Set objwst.Cells(indx,1)
obj.Dialog("Open Order").WinButton("OK").Click
If obj.Dialog("Open Order").Dialog("Flight Reservations").Exist(5) Then
obj.Dialog("Open Order").Dialog("Flight Reservations").WinButton("OK").Click
obj.Dialog("Open Order").WinButton("Cancel").Click
Reporter.ReportEvent micFail,"Open Order","Order number doesnt exist"
objwst.Cells(indx,3) = "order number doesnt exist"
objptr.WriteLine Parameter("sUname") & " tried to open order number " &
objwst.cells(indx,1) & " which doesnt exist"
Else
obj.Activate
obj.WinMenu("Menu").Select "File;Fax Order..."
obj.Dialog("Fax Order No. *.*").WinObject("Fax Number:").Type objwst.cells(indx,2)
'obj.Window("Fax Order No. *.*").RunAnalog "Track2" @@ hightlight
id_;_3016516_;_script infofile_;_ZIP::ssf1.xml_;_
obj.Dialog("Fax Order No. *.*").WinButton("Send").Click
If obj.Dialog("Fax Order No. *.*").Dialog("Flight Reservations").Exist(5) Then
obj.Dialog("Fax Order No. *.*").Dialog("Flight
Reservations").WinButton("OK").Click
Reporter.ReportEvent micFail,"Send Fax","Not able to send fax"
objwst.Cells(indx,3) = "Not able to send fax"
objptr.WriteLine Parameter("sUname") & " tried to send fax to " &
objwst.cells(indx,2) & " but not able to send fax"
obj.Dialog("Fax Order No. *.*").WinButton("Cancel").Click
Else
While obj.Dialog("Fax Order No. *.*").Exist(3)="True"
Wend
sFaxMsg = obj.WinObject("AfxWnd40").GetROProperty("Text")
If sFaxMsg = "Fax Sent Successfully..." Then
Reporter.ReportEvent micPass,"Send Fax" , "Fax Sent Successfully"
objptr.WriteLine Parameter("sUname") & " has successfully sent fax to
" & objwst.cells(indx,2)
objwst.Cells(indx,3) = "Fax sent successfully"
End If
End If
End If
Next
Else
Reporter.ReportEvent micFail,"Select Fax Order","Flight Reservation Window doesnot exist"
End If
objwbk.Save
objwbk.Close
objxl.Quit
Set objwst = nothing
Set objwbk = nothing
Set objxl = nothing
Set obj = nothing
Set objptr = nothing
Set objfile = nothing
Delete order: -
'Msgbox "Delete order"
Set objxl = CreateObject ("Excel.Application")
Set objwb = objxl.Workbooks.Open("D:Projectdeleteorder.xls")
Set objst = objwb.Worksheets("sheet1")
Set objFile = CreateObject("Scripting.FileSystemObject")
Set objptr = objFile.OpenTextFile("D:ProjectFlightDetails.txt",8)
Set obj = Window("Flight Reservation")
iRcnt = objst.UsedRange.rows.count
If obj.Exist(2)Then
For indx = 2 to iRcnt
sOnum = objst.cells(indx,1)
If sOnum>10 Then
RunAction "openord [openorder] [2]", oneIteration, sOnum, bOpen
If bOpen Then
Reporter.ReportEvent micPass,"Open Order","Opened the order to delete"
If obj.WinButton("Delete Order").GetROProperty("Enabled")="True" Then
obj.WinButton("Delete Order").Click
If obj.Dialog("Flight Reservations").Exist Then
obj.Dialog("Flight Reservations").WinButton("Yes").Click
objst.cells(indx,2) = "Deleted order number "& sOnum
objptr.WriteLine Parameter("sUname") & " has successfully
deleted the order " & sOnum
End If
End If
Else
Reporter.ReportEvent micFail,"Delete Order","Order number doesnt exist"
objst.cells(indx,2) =sOnum & " order number doesnt exist"
objptr.WriteLine Parameter("sUname") & " tried to open order " & sOnum & " but order
doesnt exist"
End If
Else
Reporter.ReportEvent micFail,"Delete Order","Cannot delete orders below 10"
objst.cells(indx,2) = "Cannot delete order number "& sOnum
objptr.WriteLine Parameter("sUname") & " tried to delete order " & sOnum & " but
cannot delete orders less than 10"
End If
Next
End If
objwb.Save
objwb.Close
objxl.Quit
Set objst = nothing [ Set objwb = nothing Set objxl = nothing Set objptr = nothing Set objfile = nothing]
Orders: -
Set objxl = CreateObject ("Excel.Application")
Set objwb = objxl.Workbooks.Open("D:Projectusers.xls")
Set objst = objwb.Worksheets("sheet1")
Set objFile = CreateObject("Scripting.FileSystemObject")
Set objptr = objFile.CreateTextFile("D:ProjectFlightDetails.txt",8)
ircnt = objst.UsedRange.Rows.Count
For indx =2 to ircnt
sUname = objst.cells(indx,1)
sPwd = objst.cells(indx,2)
RunAction "Login [ActionDemo] [2]", oneIteration, sUname, sPwd, Result
Role = objst.cells(indx,3)
Select Case Role
Case "new order"
RunAction "Action1 [neworder] [2]", oneIteration, iOrdno
RunAction "Logout [ActionDemo] [2]", oneIteration
objptr.WriteLine sUname & " has placed a new order generating order number: " &
iOrdno
objptr.Close
Case "open order"
RunAction "openord [openorder] [2]", oneIteration, iOrdno, bOpen
RunAction "Logout [ActionDemo] [2]", oneIteration
Qtp basics
Qtp basics
Qtp basics
Qtp basics
Qtp basics
Qtp basics
Qtp basics
Qtp basics
Qtp basics
Qtp basics
Qtp basics
Qtp basics
Qtp basics
Qtp basics
Qtp basics
Qtp basics
Qtp basics
Qtp basics
Qtp basics
Qtp basics
Qtp basics
Qtp basics
Qtp basics
Qtp basics
Qtp basics
Qtp basics
Qtp basics
Qtp basics
Qtp basics
Qtp basics
Qtp basics

More Related Content

What's hot

Qtp Training Deepti 3 Of 44256
Qtp Training Deepti 3 Of 44256Qtp Training Deepti 3 Of 44256
Qtp Training Deepti 3 Of 44256
Azhar Satti
 
UFT Automation Framework Introduction
UFT Automation Framework IntroductionUFT Automation Framework Introduction
UFT Automation Framework Introduction
Himal Bandara
 
Qtp Basics
Qtp BasicsQtp Basics
Qtp Basics
mehramit
 
QTP with Descriptive programming
QTP with Descriptive programmingQTP with Descriptive programming
QTP with Descriptive programming
Kuldeep Sharma
 
Interview questions in qtp
Interview questions in qtpInterview questions in qtp
Interview questions in qtp
Ramu Palanki
 

What's hot (20)

Keyword Driven Automation
Keyword Driven AutomationKeyword Driven Automation
Keyword Driven Automation
 
Qtp Training Deepti 3 Of 44256
Qtp Training Deepti 3 Of 44256Qtp Training Deepti 3 Of 44256
Qtp Training Deepti 3 Of 44256
 
QTP Training by INFOTECH
QTP Training by INFOTECHQTP Training by INFOTECH
QTP Training by INFOTECH
 
Unit testing on embedded target with C++Test
Unit testing on embedded  target with C++TestUnit testing on embedded  target with C++Test
Unit testing on embedded target with C++Test
 
Winrunner
WinrunnerWinrunner
Winrunner
 
UFT Automation Framework Introduction
UFT Automation Framework IntroductionUFT Automation Framework Introduction
UFT Automation Framework Introduction
 
Qtp Basics
Qtp BasicsQtp Basics
Qtp Basics
 
Qtp basic
Qtp basicQtp basic
Qtp basic
 
Hp Quick Test Professional
Hp Quick Test ProfessionalHp Quick Test Professional
Hp Quick Test Professional
 
Technical meeting automated testing with vs2010
Technical meeting automated testing with vs2010Technical meeting automated testing with vs2010
Technical meeting automated testing with vs2010
 
Performance testing with jmeter
Performance testing with jmeter Performance testing with jmeter
Performance testing with jmeter
 
WinRunner Training
WinRunner TrainingWinRunner Training
WinRunner Training
 
Testing
Testing Testing
Testing
 
Uft Basics
Uft BasicsUft Basics
Uft Basics
 
QTP with Descriptive programming
QTP with Descriptive programmingQTP with Descriptive programming
QTP with Descriptive programming
 
Ppt Qtp
Ppt QtpPpt Qtp
Ppt Qtp
 
Web service testing using QTP (UFT)
Web service testing using QTP (UFT)Web service testing using QTP (UFT)
Web service testing using QTP (UFT)
 
Automated Regression Testing for Embedded Systems in Action
Automated Regression Testing for Embedded Systems in ActionAutomated Regression Testing for Embedded Systems in Action
Automated Regression Testing for Embedded Systems in Action
 
Why to choose HP UFT: Automation testing tool
Why to choose HP UFT: Automation testing toolWhy to choose HP UFT: Automation testing tool
Why to choose HP UFT: Automation testing tool
 
Interview questions in qtp
Interview questions in qtpInterview questions in qtp
Interview questions in qtp
 

Viewers also liked

What is UFT? HP's unified functional testing.
What is UFT? HP's unified functional testing.What is UFT? HP's unified functional testing.
What is UFT? HP's unified functional testing.
Confiz
 
Basic controls of Visual Basic 6.0
Basic controls of Visual Basic 6.0Basic controls of Visual Basic 6.0
Basic controls of Visual Basic 6.0
Salim M
 
Introduction to visual basic programming
Introduction to visual basic programmingIntroduction to visual basic programming
Introduction to visual basic programming
Roger Argarin
 
Visual basic ppt for tutorials computer
Visual basic ppt for tutorials computerVisual basic ppt for tutorials computer
Visual basic ppt for tutorials computer
simran153
 

Viewers also liked (6)

Uft ppt
Uft pptUft ppt
Uft ppt
 
What is UFT? HP's unified functional testing.
What is UFT? HP's unified functional testing.What is UFT? HP's unified functional testing.
What is UFT? HP's unified functional testing.
 
Introduction to Unified Functional Testing 12 (UFT)
Introduction to Unified Functional Testing 12 (UFT)Introduction to Unified Functional Testing 12 (UFT)
Introduction to Unified Functional Testing 12 (UFT)
 
Basic controls of Visual Basic 6.0
Basic controls of Visual Basic 6.0Basic controls of Visual Basic 6.0
Basic controls of Visual Basic 6.0
 
Introduction to visual basic programming
Introduction to visual basic programmingIntroduction to visual basic programming
Introduction to visual basic programming
 
Visual basic ppt for tutorials computer
Visual basic ppt for tutorials computerVisual basic ppt for tutorials computer
Visual basic ppt for tutorials computer
 

Similar to Qtp basics

Qtp interview questions and answers
Qtp interview questions and answersQtp interview questions and answers
Qtp interview questions and answers
Ramu Palanki
 
Qtp interview questions and answers
Qtp interview questions and answersQtp interview questions and answers
Qtp interview questions and answers
Ramu Palanki
 
What are the features in qtp
What are the features in qtpWhat are the features in qtp
What are the features in qtp
Ramu Palanki
 
Automated Software Testing Framework Training by Quontra Solutions
Automated Software Testing Framework Training by Quontra SolutionsAutomated Software Testing Framework Training by Quontra Solutions
Automated Software Testing Framework Training by Quontra Solutions
Quontra Solutions
 
Qtp with descriptive programming
Qtp with descriptive programmingQtp with descriptive programming
Qtp with descriptive programming
medsherb
 
Qtp With Descriptive Programming
Qtp With Descriptive ProgrammingQtp With Descriptive Programming
Qtp With Descriptive Programming
Kuldeep Sharma
 
Qtp 9.2 tutorials
Qtp 9.2 tutorialsQtp 9.2 tutorials
Qtp 9.2 tutorials
medsherb
 
Pro smartbooksquestions
Pro smartbooksquestionsPro smartbooksquestions
Pro smartbooksquestions
yoummr
 
Automation testing IBM RFT - Rational Functional Tester
Automation testing IBM RFT - Rational Functional TesterAutomation testing IBM RFT - Rational Functional Tester
Automation testing IBM RFT - Rational Functional Tester
VijayChowthri Nagaprakasham
 
Qtp 9.2 examples
Qtp 9.2 examplesQtp 9.2 examples
Qtp 9.2 examples
medsherb
 

Similar to Qtp basics (20)

Qtp day 1
Qtp day 1Qtp day 1
Qtp day 1
 
Qtp interview questions and answers
Qtp interview questions and answersQtp interview questions and answers
Qtp interview questions and answers
 
Qtp interview questions and answers
Qtp interview questions and answersQtp interview questions and answers
Qtp interview questions and answers
 
What are the features in qtp
What are the features in qtpWhat are the features in qtp
What are the features in qtp
 
Why Automate
Why AutomateWhy Automate
Why Automate
 
Automated Software Testing Framework Training by Quontra Solutions
Automated Software Testing Framework Training by Quontra SolutionsAutomated Software Testing Framework Training by Quontra Solutions
Automated Software Testing Framework Training by Quontra Solutions
 
Automation testing
Automation testingAutomation testing
Automation testing
 
Automation testing material by Durgasoft,hyderabad
Automation testing material by Durgasoft,hyderabadAutomation testing material by Durgasoft,hyderabad
Automation testing material by Durgasoft,hyderabad
 
Automation testing by Durgasoft in Hyderabad
Automation testing by Durgasoft in HyderabadAutomation testing by Durgasoft in Hyderabad
Automation testing by Durgasoft in Hyderabad
 
Qtp with descriptive programming
Qtp with descriptive programmingQtp with descriptive programming
Qtp with descriptive programming
 
Qtp With Descriptive Programming
Qtp With Descriptive ProgrammingQtp With Descriptive Programming
Qtp With Descriptive Programming
 
Mykola Kovsh - Functional API automation with Jmeter
Mykola Kovsh - Functional API automation with JmeterMykola Kovsh - Functional API automation with Jmeter
Mykola Kovsh - Functional API automation with Jmeter
 
QTP 9.2
QTP 9.2QTP 9.2
QTP 9.2
 
Qtp 9.2 tutorials
Qtp 9.2 tutorialsQtp 9.2 tutorials
Qtp 9.2 tutorials
 
Pro smartbooksquestions
Pro smartbooksquestionsPro smartbooksquestions
Pro smartbooksquestions
 
UFT-1.pptx
UFT-1.pptxUFT-1.pptx
UFT-1.pptx
 
Automation testing IBM RFT - Rational Functional Tester
Automation testing IBM RFT - Rational Functional TesterAutomation testing IBM RFT - Rational Functional Tester
Automation testing IBM RFT - Rational Functional Tester
 
Automation testing
Automation testingAutomation testing
Automation testing
 
Qtp 9.2 examples
Qtp 9.2 examplesQtp 9.2 examples
Qtp 9.2 examples
 
(Agile) engineering best practices - What every project manager should know
(Agile) engineering best practices - What every project manager should know(Agile) engineering best practices - What every project manager should know
(Agile) engineering best practices - What every project manager should know
 

Recently uploaded

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Recently uploaded (20)

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 

Qtp basics

  • 1. http://www.qtpskills.com/p/qtp-chapter-iii.html QTP - Chapter I Introduction of Automation Testing: - Testing is the process of improving the quality of software. Ways to testing: - Manual testing Automation testing Manual Testing: - It is a process where we complete all the phases of STLC (software testing life cycle) by manual, is called as manual testing Draw backs of manual testing: - Time consuming More number of human resources are required Tiredness of the testers Human errors (Less accuracy) Simultaneous actions are almost impossible Automation Testing:- Automation testing is a process where we can test the application with the help of Automation Tool Benefits of Automation Tool:- Fast: - It runs the script faster than human beings. Reusable: - We can reuse the scripts in different regression testing. Cost reduction: - It reduces number of resources and hence less budget. Accuracy: - No tiredness and hence good accuracy results. Disadvantage of Automation Testing:- Proficiency is required to write automation test scripts. It is expensive to buy. In all areas automation testing is not possible. Difference between Manual and Automation Testing:- Manual Testing:- 1. Testing is implemented by manually 2. 2. It is the best suite for application which the numbe of test cycles are less 3. The test case development is less 4. The test case execution time is more 5. The test data needs to be provide by manually 6. The test reports can be generated by manually 7. Defects need track manually 8. Organization point: the cost of manual testing is more 9. The programming knowledge is optional Automation Testing:- 1. Testing is implemented by using tools
  • 2. 2. It is the best suite for application which number of test cases less 3. Test script development time more 4. Test script execution is time is less 5. The test data can be generated by tool it self 6. The test cases can be generated by automatically 7. Defects can be tracks automatically 8. the cost of automation testing is more 9. A minimum programming knowledge is required Types of testing can be done by Automation: - Functional (Positive and Negative) testing Regression Testing Performance Testing Usability Testing Functional Tools:- Quick Test Professional (QTP) IBM rational functional tester Winrunner Selenium Test complete Performance tools:- Load runner J meter Test complete Test Management Tools:- Test direct Quality center Bugzilla Rally Clear quest Things to done before Automation Testing: - 1. Return on investment (ROI) 2. Tool selection 3. Identify Framework 4. Automation feasibility Automation feasibility: - It is a process of identifying what test case can be automated and cannot be automated. This will be done by automation tester for their respective modules. What test case can be Automated: - The test case needs to be run on every build The test case needs to be run on multiple test data Multiple browser compatibility test cases Application objects which do not change in short time What test case cannot be Automated: - Security related test cases
  • 3. Idle time functionalities Batch processing requirements Graphs related test cases Usability test cases Documentation verification testing 3rd party objects requirements. Ex: - PDF, Printers etc... > After completion of Automation feasibility we go for estimations Example: - Finding number of resources to automate for 800 test cases in 100 days Number of test cases to designed per day = 800/100=8 test One resource 2 scripts per day How resources need if 8 scripts per day =8/2=4 resources Example: - Finding number of days to automate 800 test cases with 4 resources One resource 2 scripts/ day 4 resources 4*2=8 scripts/day Number of days = Total test cases/per day scripts= 800/8=100 days Automation testing process: - 1. ROI [Return on Investment] 2. Tool selection 3. Test cases feasibility analysis 4. Preparation of automation test plan document 5. Framework designing 6. Designing test scripts for manual test cases 7. Involve in code walkthroughs and code inspections 8. Test scripts debug 9. Involving in regression support by executing test scripts as a batch 10. User acceptance testing QTP Automation Chapter II Introduction to QTP (Quick Test Professional) Type of Tool: - it is a functional Regression Testing Tool Earlier Version: - 5.5 Released in 2001 6.0 Released in 2002 6.5 Released in 2003 7.0 Never Released 8.0 Released in 2004 8.2 Released in 2005 9.2 Released in 2007 9.5 Released in 2007 10.0 Released in 2009 11.0 Released in 2011(this version is called as UFT: - Unified Functional Tester) 11.5 Beta version 24/12/2012 Scripting Language: - VB script, java script, Perl script
  • 4. Note: - While latest versions of QTP supports all most all versions. License in QTP: - Seat license: - it is 1:1 license (this is single user license) Concurrence license: - This is a network based license which can share by all the machines in net work. Launching QTP: -*** Step 1: - currently we are using client license, so we need to connect to the client machines. We can connect to the client machine with help of Citrix access get way/ VAP/ Remote Desktop (MSTSC) Step 2: - Click on start > All Programs > Quick Test Professional > select Quick Test Professional Step 3: - While lunching QTP it verifies QTP license and add-in license Step 4: - It Opens add- in Manager Windows with add-ins Step 5: - Select required add- in and click ok button. Add-in Manager: - > It displays all the available add-ins, by default Quick Test Professional provides ActiveX, VB, and Web Note: -by default QTP supports windows environment and hence it is not showing is add-in manager window. > Add-in manager is used to select required environment (Add-in) to make compatible with required environment. > Apart from all this add-ins, if user wants any extra add-ins then user need buy from HP and install.
  • 5. Architecture of QTP: - QTP window is divided in to bellow parts. 1. Test Pane 2. Active Scripts 3. Data Table 4. Information Pane 5. Debug viewer Pane 6. Missing resource Pane 7. Tool option 1. Test Pane: - It is an area where we can write a new test script or to open existing test scripts. It is divided in to 2 views 1> Expert view: - It displays test script in VB Script format 2> Keyword view: - it displays test script in GUI format. It is divided into bellow views 1. Item: - displays fields names 2. Operation: - Displays operation names (Actions performed) 3. Value: - it displays test data. 4. Documentation: - it displays a sentence about item, operation and value. Note 1: - If we do any operation in expert view it effects to keyword and vice versa Note 2: - If we have any syntax errors in expert view not able to navigate to keyword view Note 3: - We can also design test scripts from keyword view. 2. Active Screen: - it is displays a screen shot for each and every VBScript statement. (view menu --> Active Screen) 3. Data Table: - It holds multiple Test Data. It is looks like ms-excel sheet (it contains 65, 536 rows and 256 columns). By default data table provides following 2 sheets 1.Global, 2. Action1 4. Information Pane: - (Navigation:- view menu--> Information ) > It displays syntax error massages. When we save test script. Note: - After save a test script QTP internally compiles the script and display syntax errors in information pane > Information pane contains bellow information Details: - It displays syntax error information Item: - It displays script name Action: - It displays Action name Line no: - It displays error line number 5. Debug viewer Pane: - It is used to find the logical errors and variable values during script execution debug viewer) (view 6. Missing resource: - It displays not available file path which we associated to test script. 7. Tool option: - these are menu options where we can select required menu options. QTP Chapter III Introduction to VBScript Display user defined message: MsgBox Function: -It displays given message and waits for the user to click OK button or close dialog Ex: - MsgBox “Welcome to QTP World” Comments in QTP: - By using single cots („) user can give the comments for scripts Display Message with Required Dialog Title and Buttons: -
  • 6. Syntax: -MsgBox “<message>”, button no, “<dialog title>” Ex: -MsgBox “Welcome to QTP World”, 0 “sample” Here: - 0 is the number for the different types of buttons we have 0, 1, 2, 3, 4, 5, 16, 32…etc. go to MsgBox help by pressing function1 (F1). “Sample” is dialog title. Print Statement: - It displays user given message in Quick Test Print Log window It doesn‟t require any user interaction It will works in QTP only Note: - MsgBox is defined in VBScript Print statement defined in QTP Display a message and Close: -** Set obj= CreateObject (“Wscript.Shell”) obj.Popup “Welcome to QTP World”, 5, “Sample” Here: - number 5 is seconds to close the popup Reading Values during runtime: - InputBox: -it displays a prompt and waits for the user, to enter text and click OK/ Cancel button Syntax: - <variable>= InputBox (“<message>”) Ex: - Val = InputBox (“Enter any Value”) MsgBox Val Operators: - Types of VBScript Operators: - 1. Arithmetic Operators 2. Assignment Operator 3. Comparison Operator 4. Concatenation Operators 5. Logical Operators Arithmetic Operators: - These are used to perform Mathematical operations on given values. 1. ^ operators: -It raises a number to the power of an exponent Ex: - MsgBox 2^3 „returns 8 (2*2*2) 2. * operators: - Multiplies Ex: - MsgBox 2*3 „returns 6 3. / operators: - divides Ex: - MsgBox 2/3 „returns 0.5(Float value) 4. operators: - divides Ex: - MsgBox 2/3 „returns 0(Integer value) 5. MOD operators: - divides Ex: - MsgBox 7 mod 5 „returns 2 (7 divided by 5) 6. + operators: - Sum of given number 7. - operators: - Finds difference between given number
  • 7. Assignment Operator: - = operator: - assigns a given value to a variable Ex: - Val = 10 MsgBox Val Comparison Operator: - These are used to compare two given values Ex: - Val1=10 Val2 = 20 MsgBox Val1 < Val2 „Returns True MsgBox Val1 > Val2 „Returns False MsgBox Val1 <> Val2 „Returns True MsgBox Val1 = Val2 „Returns False Concatenation Operator: - & operator: -It concatenates/ appends to given values Ex: - Val1= “Hi” Val2 = “Bye” MsgBox Val1 & Val2 (Without space) MsgBox Val1 &” ” & Val2 (With space) Logical Operator: - AND operator: - Perform logical conjunction on 2 given conditions OR operator: - Perform logical disjunction on 2 given conditions NOT operator: - Perform logical disjunction on 2 given conditions
  • 8. If….Then….Else….If: - Maintaining conditional statement, in another conditional statement Syntax: - If<condition> Then <Statement> Else If<condition>Then <Statement> End If End If Ex: - Apply If….Then….Else….If to bellow scenario, Do you know testing tool course. If yes then find do you know QTP. If QTP know then display a message Try for JOB. If QTP doesn‟t know then display a message “Go to login f1 to learn QTP”. If testing tool doesn‟t know then display a message “Got login f1 to learn TT”. Val2 = InputBox ("Do you know Testing Tools?") If Val2="yes" Then Val3= InputBox ("Do you know QTP?") If val3="yes" Then MsgBox "Try for job" Else MsgBox "Go to login F1 to learn QTP" End If Else MsgBox "Go to Login F1 to learn TT" End If Select….Case: - It is used to execute a group of statements depends on multiple conditions Syntax: - Select Case <variable> Case 1 <condition> <Statement> Case 2 < condition > <Statement> Case 3 < condition > <Statement> Case Else „Optional <Statement> Ex: -Display one number and display a day name Val = InputBox ("Enter any number") Select Case Val Case 1 MsgBox “Sun Day" Case 2
  • 9. MsgBox "Mon Day" Case 3 MsgBox “Tue Day" Case 4 MsgBox "Wed Day" Case 5 MsgBox "Thu Day" Case 6 MsgBox "Fri Day" Case 7 MsgBox "Sat day" Case Else MsgBox "Invalid Number" End Select Variable Declaration: - Variable: -It is a storage place where we store variable. Declaration: -We declare the variable by using DIM statement. Dim Var1, Var2… Note: - **** 1. Variable names should be meaning full 2. Variable name should explain what type of data we are storing in it Ex: - If store INTIGER then we starts with „i‟ If store STRING then we starts with„s‟ If store DOUBLE then we starts with„d‟ If store BOOLEAN then we starts with „b‟ If store DATE then we starts with „dt‟ If store TIME then we starts with„t‟ 3. Variable names are not case sensitive but we follow standards 4. Variable names starts with small latter, if it contains multiple words then second word on wards the first latter should be a capital latter Ex: -Dim sEmpName, dEmpSal, dtDob, iEmpId…. 5. Default variable is EMPTY 6. When we give the values (numbers) from InputBox for „+‟ operator it treats as String Integer and concatenates the values. For „-„, „*‟, „/‟ operators converts the numbers from String Integers into integer values and do the mathematical operations 7. VBScript variables are variant data type (any kind of data) Ex: -Variable: - MsgBox Krishna + sreekar „Returns 0 (zero) MsgBox Krishna - sreekar „Returns 0 (zero) MsgBox Krishna * sreekar „Returns 0 (zero)
  • 10. MsgBox Krishna / sreekar „Returns Overflow error Massage Strings: - MsgBox “Krishna” + “sreekar” „Returns Appends / concatenates the strings MsgBox “Krishna” - “sreekar” „Returns Error msg as not able to perform String subtraction MsgBox “Krishna” * “sreekar” „Returns Error msg not able to perform String Multiplication MsgBox “Krishna” / “sreekar” „Returns Error msg not able to perform String Division Strings and Variable: - MsgBox “Krishna” + sreekar „Returns krishna MsgBox “Krishna” - sreekar „Returns Error MsgBox “Krishna” * sreekar „Returns Error MsgBox “Krishna” / sreekar „Returns Error String Integers: - MsgBox “10” +”20” „Returns 1020- appends/ concatenates MsgBox “10” -”20” „Returns -10 MsgBox “10” *”20” „Returns 200 MsgBox “10” /”20” „Returns 0.5 String Integers and Numbers: - MsgBox “10” + 20 „Returns 30 MsgBox “10” - 20 „Returns -10 MsgBox “10” * 20 „Returns 200 MsgBox “10” / 20 „Returns 0.5 String and Numbers: - MsgBox “krishna” + 20 „Returns Error Massage MsgBox “krishna” - 20 „Returns Error Massage MsgBox “krishna” * 20 „Returns Error Massage MsgBox “krishna” / 20 „Returns Error Massage In VBScript declaring variables are not mandatory, But we are declaring [Q: - Is variable declaration is mandatory in VBScript? answer is no then next...Q: - Why?] Option Explicit: -*** It displays error massage for undefined variable names. Option Explicit is must declared in the first line of the program. Ex: - OptionExplicit Dim sEmpname sEmpName “sreekar”
  • 11. MsgBox sEName „Returns Error Massage for not defined sEName variable Note: - Variable names should not be a KEY word Loop Statement: - These are used to execute a group of statements for multiple times VBScript Loop Statements: - 1. For… Next 2. While… Wend 3. Do… Loop For…Next: - It executes a script for required number of given times Syntax: - For <variable> = <Start Position > To < End Position > [Step] <Statement> [ExitFor] Next {Here written in [] are optional} Ex: - Display a massage “QTP” for 5 times For index = 1 To 5 MsgBox index Next > In bellow code a and z treats as variable returns empty values so answer is 0 For index = a To z MsgBox index Next > In bellow code a and z treats as variable returns empty values so answer is 0 For index = “a” To “z” MsgBox index „Returns error massage Next Ex: - Display numbers from 5 to 10 > In bellow given string integers are converts in to integers For index = “5” To “10” MsgBox index Next STEP Command: Ex: - For index = 1 To 5 Step 3 MsgBox index „Returns 1, 3 Next Ex: - Display even numbers 2 to 10 For index = 2 To 10 Step 2 MsgBox index „Returns 2, 4, 6… Next
  • 12. Ex: - Display odd numbers from 1 to 10 For index = 1 To 10 Step 2 MsgBox index „Returns 1, 3, 5… Next Ex: - Display numbers from 5 to 1 For index = 5 To 1 Step -1 MsgBox index „Returns 4, 3… Next ExitFor: - Ex: - For index = 1 To 10 Step 2 MsgBox index „Returns 1 and exits from For loop ExitFor Next Ex: - For index = 1 To 10 Step 2 MsgBox index If index = 3 Then ExitFor EndIf Next While… Wend: - It execute group if statements until condition is True Syntax: - While <condition> <Statement> Wend Ex: - Display a massage “QTP” for 5 times index = 1 While index <= 5 Print "QTP" index = index+1 Wend
  • 13. Ex: -Display numbers from 1 to 10 index = 1 While index <= 10 Print index index = index+1 Wend Ex: - Display odd numbers from 1 to 10 index = 2 While index <= 10 Print index index = index+2 Wend Do… Loop: - It executes group statement until condition becomes True Syntax: - Do <condition> <Statement> Loop While <condition> Ex: -Display a massage “QTP” for 5 times index = 1 Do Print "DTP" index = index+1 Loop While index = 5 Ex: -Display numbers from 1 to 10 index = 1 Do Print index
  • 14. index = index+1 Loop While index <= 10 Functions Functions are used for scripts reusability 1. Built-in Functions 2. User Defined Functions Built-in Functions: - These are pre defined by VBScript Access functions in QTP Category as Functions Library as Built-in Function find the functions in StepGenerator Insert MenuOperation drop down Note 1: - Function names are not Case Sensitive
  • 15. Note 2: - We follow standards like function name starts with capital later if it contains multiple words then 2nd word on words 1st later should be a capital latter 1. Abs() [Absolute]: -It returns absolute value to a given number Ex: - MsgBox Abs (10) „Returns 10 MsgBox Abs (-10) „Converts the –ve in to +ve „Returns 10 MsgBox Abs (10.56) „Returns 10.56 MsgBox Abs (-10.56) „Returns 10.56 MsgBox Abs ("10") + Abs ("20") „Returns 30 – Converts the string into Integer Value 2. Asc(): - It returns ASCII to given Character Ex: -MsgBox Asc ("a") „Returns 97 MsgBox Asc ("z") „Returns 122 MsgBox Asc ("A") „Returns 65 MsgBox Asc ("Z") „Returns 90 3. Chr(): - It returns ASCII to given Character Ex: - MsgBox Chr (97) „Returns a MsgBox Chr (122) „Returns z MsgBox Chr (65) „Returns A MsgBox Chr (90) „Returns Z 4. CInt(): - It Converts String Integer in to Integer Ex: - iVal1 = "10" iVal2 = "20" MsgBox iVal1+iVal2 ' Returns 1020 MsgBox CInt (iVal1) +CInt (iVal2) ' Returns 30 Ex: - 10.56 the CInt Converts into 11 iVal1= "10.56" iVal2= "-20.78" iVal1= iVal1*100 iVal2= iVal2*100 MsgBox (iVal1+iVal2) / 100 5. CStr(): - It converts given value into Strings iVal1 = 10 iVal2 = 20 MsgBox iVal1+iVal2 Returns 30 MsgBox CStr (iVal1) + CStr (iVal2) „Returns 1020 MsgBox CStr (iVal1) – CStr (iVal2) „Returns -10 Date and Time Factions 6. Date: - It returns current system Date in MM/DD/YYYY format Ex: - MsgBox Date
  • 16. 7. Time: - It returns current system Time in HH/MM/Sec format 8. Ex: - MsgBox Time 9. Now(): - It returns current system Date & Time Ex: - MsgBox Now 10. DateAdd(): - This function add/ subtracts given date or time, given date and time Ex: - MsgBox DateAdd ("yyyy", 1, Date) „Returns Year with adding 1 to the current year MsgBox DateAdd ("q", 1, Date) „Returns Quarter with adding 1 to the current Quarter MsgBox DateAdd ("m", 1, Date) „Returns Month with adding 1 to the current Month MsgBox DateAdd ("y", 1, Date) „Returns Day of year with adding 1 to the current Day of year MsgBox DateAdd ("d", 1, Date) „Returns Day with adding 1 to the current Day MsgBox DateAdd ("w", 1, Date) „Returns Weekday with adding 1 to the current Weekday MsgBox DateAdd ("ww", 1, Date) „Returns Week of year with adding 1 to the current Week of year MsgBox DateAdd ("h", 1, Date) „Returns Hour with adding 1 to the current Hour MsgBox DateAdd ("n", 1, Date) „Returns Minute with adding 1 to the current Minute MsgBox DateAdd ("s", 1, Date) „Returns Second with adding 1 to the current Second MsgBox DateAdd ("yyyy", 8000, Date) „Returns Error because year above 10000 11. DateDiff (): - This function is used to find the difference in between given 2 dates or 2 times. In day, Month, Year, hour, Minutes, Seconds intervals Syntax: -MsgBox DateDiff (Interval, date1, date2) MsgBox DateDiff ("d", Date,"01-01-2013") 'Returns -2 (My System date 03-01-2013) MsgBox DateDiff ("d", "01-01-2013", Date) 'Returns 2 (My System date 03-01-2013) 12. DatePart(): - It is used to retrieve required interval date or time from given date or time Syntax: - MsgBox DatePart (Interval, Date/ Time) MsgBox DatePart (“d”, Date) MsgBox DatePart (“m”, Date) MsgBox DatePart (“yyyy”, Date) 13. Day(): - It retrieves day from given date Ex: - MsgBox Day (Date) 14. Month(): - It retrieves Month from given date Ex: - MsgBox Month (Date) 15. MonthName(): - It retrieves the name of the month from given number from 1 to 12 Ex: - MsgBox MonthName (Date) 16. Year(): - It retrieves Year from given date Ex: - MsgBox Year (Date) 17. WeekDay(): - It retrieves Weekday from given date Ex: - MsgBox WeekDay(Date) 18. WeekDayName(): - It retrieves WeekDayName from given number(1-7) Ex: - MsgBox WeekDayName (1) „Returns Sunday
  • 17. MsgBox WeekDayName (WeekDay (Date)) „Returns current WeekDayName Boolean Functions: - 19. IsDate (): -It retrieves Boolean value for given expression is date or not. It returns True if given value is date else false Ex: - MsgBox IsDate (“Suresh”) „Returns False MsgBox IsDate (“3-01-2013”) „Returns True 20. IsEmpty (): -It retrieves Boolean value for given value is Empty or not. It returns True if given value is Empty else false Ex: - Dim val1, val2, val3 Val1 = 10 Val2 = Null MsgBox IsEmpty(Val1) „Returns False MsgBox IsEmpty(Val2) „Returns False MsgBox IsEmpty(Val3) „Returns True 21. IsNull (): -It retrieves Boolean value for given value is Null or not. It returns True if given value is Null else false 22. IsObject (): - It retrieves Boolean value for given expression is Object or not. It returns True if given value is Object else false Ex: - Dim Val1, Obj Val1 = 10 Set obj = CreateObject (WScript. Shell) MsgBox IsObject (Val1) „Returns False MsgBox IsObject (Obj) „Returns True 23. IsNumeric (): - It retrieves Boolean value for given expression is Numeric or not. It returns True if given value is Numeric else false Ex: - Dim val1, val2, val3 Val1 = 10 Val2 = 13.45 Val3= “suresh” MsgBox IsNumeric (Val1) „Returns True MsgBox IsNumeric (Val2) „Returns True MsgBox IsNumeric (Val3) „Returns False String Functions 24. Left (): - It returns number of characters from left side of a given string Ex: - sString = “My Name is Suresh” MsgBox Left (sString, 4) „Returns My N 25. Right (): - It returns number of characters from right side of a given string Ex: - sString = “My Name is Suresh” MsgBox Right (sString, 4) „Returns resh 26. Mid (): -*** It returns a substring from a given String System: - MsgBox Mid (String, start position [, Number of characters]) Ex: - Ex: - sString = “My Name is Suresh”
  • 18. MsgBox Mid (sString, 4, 7) MsgBox Mid (sString, 4) MsgBox Mid (sString, 100) MsgBox Mid (sString, 100, 1) sString = "Rs:1000/-" MsgBox Mid (sString, 4, 7) ' Returns 1000/- MsgBox Mid (sString, 4, 4) ' Returns 1000 'To get any number MsgBox Mid (sString, 4, Len (sString)-5) ' Returns 1000 27. Len(): - ***It returns number of characters from given string Ex: - sString = “My Name is Suresh” MsgBox Len (SString) 28. Replace(): - This function is used to replace a text with another text in given text Syntax: - Replace (String, replacing text, new text) Ex: - sString = "My name is suresh" MsgBox Replace (sString, "suresh", "babu") MsgBox Replace (sString, "is", "") 29. LTrim(): - It removes all spaces from Left side of a given string [Ex: - MsgBox LTrim(sString)] 30. RTrim(): - It removes all spaces from Right side of a given string [Ex: - MsgBox RTrim(sString)] 31. Trim(): - It removes all spaces from Left and Right side of a given string 32. LCase(): - It converts given text in lower case letters 33. UCase(): - It converts given text in upper case letters Ex: - MsgBox LCase (“My Name Is SURESH”) MsgBox UCase (“My Name Is SURESH”) 34. StrReverse(): - ***It displays / retrieves a reverse text for given string/ text sString= “suresh” MsgBox StrReverse (sString) Without using StrReverse:- Dim sString sString = “suresh” For index = Len (sString) To 1 Step -1 str = str & Mid(sString, index,1) Next Print str 35. InStr() and InStrRev(): - It retrieves the first occurrence position of the given text in actual text sString = “My name is suresh your name is babu” MsgBox InStr (sString,”suresh”) „Returns the position of„s‟ from suresh MsgBox InStr (sString,”name”) „Returns 4 first occurrence of name MsgBox InStr (sString,”babu”) „Returns 0 MsgBox InStrRev (sString,”name”) „Returns 24 Last occurrence of name MsgBox InStr (14, sString,”babu”) „Returns 0: suresh is not found from 14th position 36. StrCompp(): - It is used to compare two given strings
  • 19. 37. String(): - It is used to display the string in number of times Ex: -MsgBox String (5, *) „Returns ***** 38. TypeName(): -It returns the data type for the given variable Ex: - Dim Val Val = 10 MsgBox Val 'Returns 10 MsgBox TypeName (Val) 'Returns Integer Val = 10.05 MsgBox Val 'Returns 10 MsgBox TypeName (Val) 'Returns Double Val = "Suresh" MsgBox Val 'Returns 10 MsgBox TypeName (Val) 'Returns String 39. Split (): - It is used to split the text with given delimiters 40. Arrays Arrays are used to store multiple values in a variable Declaration: - 1> Static Array declaration Dim sName (3) 2> Dynamic Array declaration Dim sName ()
  • 21.
  • 22. 9. Write a script to find the SUM of odd number up to given number 10. Write a script to find the SUM of even number up to given number 11. Write a script to find given Text/ Numbers is palindrome or not [madam reverse madam] sString = UCase(InputBox("Enter the String/Number:"))
  • 23. rString = StrReverse(sString) If StrComp (sString,rString) = 0 Then MsgBox “It is a Palindrome" Else MsgBox “It is Not a Palindrome" End If 12. Write a script to find Factorial of given number [5*4*3*2*1=120] Option Explicit Dim iVal1 ,iVal2, iFact iVal1= Int (InputBox ("Enter a Number :")) iFact = 1 iVal2=1 Do while iVal2 <=iVal1 iFact = iFact * iVal2 iVal2=iVal2+1 Loop Print iFact 15. Write a script to display * as bellow with respect to given value Option Explicit Dim iVal, sString,index,index1 sString="" iVal = 5 ' InputBox ("Enter a Number") For index = 1 To iVal For index1 = 1 To index sString = sString & " * " Next
  • 24. Print sString sString="" Next 16. Write a script to display * as bellow with respect to given value 17. Write a script to display * as bellow with respect to given value 9 programs to write for this 1) Pro1 Option Explicit Dim iVal, sString,index,index1 sString="" iVal = 5 ' InputBox ("Enter a Number") For index = iVal To 1 Step-1 For index1 = 1 To index sString = sString & " * " Next Print sString sString="" Next 2) Pro 2 Option Explicit Dim iVal, sStar,index,index1,iSpace iVal = 5 For index = iVal To 1 Step-1 For index1 = 1 To iSpace sStar= sStar & " " Next For index1 = 1 To index sStar = sStar & "*" Next Print sStar sStar ="" ' Removing the value after print iSpace= iSpace + 1' Increasing the spaces for next iteration Next '############################################################################################# '######### Program to write a character in a particular pattern using VBS ######################### '############################################################################################# 'Declaring variables Dim MainCounter,TempCounter,sStr,sTempStr,sMainStr,PatternChar 'Initializing variables PatternChar = "*" sStr = "" 'Reading from Input and initializing MainCounter = InputBox("Enter any number") If MainCounter = "" Then MainCounter = 9 End If MainCounter = Abs(MainCounter)
  • 25. TempCounter = MainCounter 'Looping twice the supplied value to draw the pattern and reverse it For MainIndex = 1 to MainCounter * 2 'Increase the tempCounter for drawing the pattern and 'Decrease the tempcounter to draw the pattern in reverse order If Abs(MainIndex) <> 1 and Abs(MainIndex) <> MainCounter + 1 Then If MainIndex <= MainCounter Then TempCounter = Abs(TempCounter) - 1 Else TempCounter = Abs(TempCounter) + 1 End If End If sTempStr = "" iSpace = "" 'Looping to Create the pattern for a single row For indx = 1 to TempCounter sTempStr = sTempStr & PatternChar Next 'manipulating space for a row iSpace = Space((Abs(MainCounter)-Abs(TempCounter)) * 2) 'Adding the space for a single row sStr = sStr & sTempStr & iSpace & sTempStr & vbNewline Next 'sStr= sStr & vbNewline & StrReverse(sStr) 'MsgBox sStr 'Writing the pattern to a txt file in D drive Dim filesys, testfile Set filesys = CreateObject("Scripting.FileSystemObject") Set testfile= filesys.CreateTextFile("d:PatternDrawnFromVbs.txt", True) testfile.WriteLine sStr testfile.Close Example: - write a script to retrieve India in given string “I love India” sVal = "i love InDiA" sVal = Split(s," ") MsgBox sVal(UBound(s)) Application (Window, VB, Java, Dot Net, Web) Script Application Script: - Script 1: -Write a script to enter student details Note: - Before writing a VBScript with respect to application we need to know bellow 5 information‟s 1. Object Name 2. Object Class Name 3. Object Parent Object Name
  • 26. 4. Object Parent Object Class name 5. Method Name. To perform operation Note: - Object SPY To know about the object use Object SPY in TOOL MENU For Web Application iHwnd = Browser("Gmail")GetROProperty("hwnd") „ first 2 lines to activate the browser Window("hwnd:="&iHwnd).Activate Browser("Student").Page("Student").WebEdit("").Set "Sreekar" Browser("Student").Page("Student").WebEdit("Course").Set "QTP" Browser("Student").Page("Student").WebButton("Submit").Click QTP Chapter IV Chapter - 4 Object Repository: - It is a storage place, where we store objects and their information Note: - Before designing or executing a test script we need to add objects to Object Repository for recognition of objects by QTP. Else QTP is not able to understand the objects displayed the errors while executing the script Object Repository select Navigation: - Resource menu Or Click Object Repository Or Cntrl + R Application under test [AUT]: -It means which application we need to test is called AUT. Adding Objects to Object Repository: - We can add objects to Object Repository by manually or by Recording Adding Objects to Object Repository By Manually: - Click Ad Objects to local icon Open Object Repository Open Application under test [AUT] Select required object with the help of handler pointer If it is parent object displays Filter Options [Selected objects only, Default Object Click OK button Select required option Click OK Button. Types, All Object Types, Selected Object Types] Note: - Every Action maintains individual Object Repository in Object Repository
  • 27. Options in Object Repository: - We have Operations as follows ADD: - We can add objects to Object Repository by manually or by Recording Select Rename Right Click on required object Rename: - Open Object Repository Check YES in Select Delete Right Click on required object Delete: - Open Object Repository Confirmation Note-1: - Before executing the script, we make sure that the AUT is open Note-2: - If we Re-name the Object name in Object Repository it affects to test script Note-3: - If we do any modification on objects in test script it will not/ doesn‟t affect to Object Repository Note-4: - If we save a test script Object Repository also saves for the same test script Note-5: - We can drag objects from Object Repository to test script. We write test script in Keyword View. Types of Object Repository: - We have two types of Object Repository 1. Local Action (or) per Action Object Repository 2. Shared Object Repository Local Action (or) per Action Object Repository: - Maintaining Repositories in Action independent is called as Local Action (or) Per Action Object Repository. Ex: - A1R (Action Repository) Objects Objects >A2R (Action Repository) Objects >A3R (Action Repository) Note1: - Local repository saves the file with “.mtr” [Mercury Test Repository] while save the script Shared Objects Repository: - Creating and maintaining a single repository for multiple actions called as Shared Object Repository. EX: - Creating Shared Creating Shared Object Repository: - Export Local File Add object to Object Repository Open Object Repository Open AUT Save the file in required path with “.tsr” [Test Shared Repository] Objects After creating a shared ObjectRepository we need to associate to required test script for use. We can associate in bellow ways 1. By Navigation 2. By Scripting By Navigation: - Browse and Open Click Add Button Associate Repositories Repository Open required test script click OK button select Required Action SOR [Shared Object Repository] By Scripting: - Syntax: - RepositoriesCollection.Add “SOR File Path” Ex: - RepositoriesCollection.Add “D:sureshORxxxx.tsr”
  • 28. Note1: - RepositoriesCollection.Add is a static association i.e. if we write the statement in action, then it associate to action1 Repository Note2: - After script execution SOR disassociate by default. Note3: -For better maintenance we use only one shared object repository. Working with Shared Object Repository/ Operations in SOR: - Directly we are not able to modify any operations on SOR file. We use Object Repository Manager [ORM]. Brows and open required SOR Click open folder icon object Repository Manager Navigation: -Resource Menu Click Save. on Objects perform required operations (Add, Rename, Delete) click Enable edit Icon file Note: - if we do any modification in SOR file it changes in all associated object repositories. Merging Shared Object Repository: - [we won‟t use] Navigation: -Browse and Open select Object Repository Merge tool Tools select ORM Resources menu save the file .tsr click save icon primary and secondary files Types of Objects With respect to OR we have 2 types of objects. 1. Test objects 2. Runtime Object Test Object: -Objects which are in OR are called as test objects. Runtime Objects: - objects which are in AUT are called as runtime objects. Note: - Every Test object is a run time object. Note: - Every runtime object may or may not be a test object Working with Test Objects: - 1. GetToProperty() 2. GetToProperties() 3. SetToProperty() GetToProperty (): - It is used to retrieve test object given, property value during run time. Syntax: - Ex: - MsgBox dialog(“login”).WinButton(“Help”).GetTOProperty (“Text”) „Returns Help MsgBox Dialog(“login”).GetToProperty(“text”) Note: - 1. If given property is invalid or not available in Object Repository. It retrieves EMPTY. 2. Property names are not case sensitive GetTOProperties(): - It is used to retrieve multiple property names and its values for a test object, from OR during run time. Ex: - MsgBox Dialog(“login”).GetTOProperties() „ Returns ERROR {Script 2 is an example for this} Script No 2: - Write a script to retrieve property names and values per a login object Set sPropertyLst = Dialog("Login").GetTOProperties 'MsgBox sPropertyLst.Count For index = 0 To sPropertyLst.Count-1 Print sPropertyLst(index).Name & VbTab & sPropertyLst(index).Value Next Set sPropertyLst = Nothing SetTOProperty(): - It is used to change the test object property values during run time. Whenever object properties are changing at runtime we use this method:
  • 29. Syntax: - Ex: - Dialog(“login”). SetTOProperty “text”,”sreekar” Working with Run Time Objects: - GetROProperty(): - It used to retrieve run time object property value during run time Syntax: - Ex: - MsgBox Dialog(“login”).GetROProperty(“text”) [Above code will retrieve QTP identified properties {in object spy}] Note: -*** If we want to retrieve Native Properties for an object we use “Object()” Syntax: - [Native Properties are developers given properties {in object spy}] Work Out: - Go through the button, text box, browser, page, link for Identified Properties and Native Properties Adding objects to OR by Run Time Types of Recording: - 1. Normal or Standard Recording 2. Analog Recording 3. Low-Level Recording Normal or Standard: - It is used to record standard objects like Window, Web, VB, Java, Dot Net…Etc. select desired environment (Web/ Windows) Record Button Navigation: - Open application (AUT) observe that script is generated in click Stop perform operations on AUT Click OK Click Apply test pane and respective objects added in OR. Analog Recording: - Analog recording is used to record diagrams, signatures, graphs…etc. It generates a single statement for every start and stop recording. Navigation:- Click Select Environment window or web Click Recording in QTP Open AUT Select Record relative to the following window Select Analog Recording from Automation Menu OK perform Click start analog record button with help of handler point select AUT radio button Click Stop Recording in QTP. operation Low-Level Recording: - It is used to record minimum operations on non-supported environments Select Web/Windows Select desired Environment Click Record in QTP Navigation: -Open AUT click STOP Recording. Perform operations on AUT Low Level Recording from Automation Menu Object Repository Standards: -
  • 30. 1. What is an Object? 2. How QTP is recognizing objects? 3. What is OR? 4. What is your approach for writing a test script? 5. What is the default OR? 6. How do you add object to OR? 7. What is extension of PerAction of Local repository? 8. How do you create local Repository? 9. How many objects I can store in QTP test script?—2MB 10. How to create SOR? 11. What is difference between PerAction and SOR? 12. How many SOR files you have created for your project? 13. What is the file extension of SOR file?--.tsr 14. Where do you maintain all SOR files in your testing process? 15. Have you merged SOR files? 16. Why do you go for merging SOR files? 17. Can we do merge more than 2 SOR files at a time, if it is not then how do you merge more than two SOR files? 18. How do you merge PerAction Repository? 19. How many objects are there and what are they?
  • 31. 20. How do you create test objects? 21. What are the methods you can find for Test Objects? 22. What is the difference between GetToProperty and GetToProperties method? 23. Write a test script for retrieving multiple properties and their values for a object? 24. How do you handle, if test object properties are dynamically changing during run time? 25. How do you retrieve object information during runtime? 26. What is the deference between GetToProperty and GetROProperty? 27. Which method you are using for retrieving object information GetToProperty or GetROProperty? 28. Who will create SOR? 29. How do you work with SOR? QTP - Chapter V Check Points Check points are used to validate Object Properties, Comparing Text, Comparing Images, Validate Database…etc. [OR] Check point is a verification point, it takes expected result from the user and compares with actual results during execution and provides test results. Types of Check Points: - There are 9 Checkpoints available in QTP: 1. Standard check point 2. Text check point 3. Text area check point 4. Bit map check point 5. Data base check point 6. Image checkpoint 7. Table checkpoint 8. XML Check point (from Application) 9. XML Check point (from Resource) 1. Standard Checkpoint: It is used to validate object properties Navigation: -Open AUT Click Record in Qtp Insert Menu Check Point Select Standard Checkpoint Select Expected properties and With help of handler Select Required Object Click on OK button Values Click on OK Button. Syntax: - Ex: - Dialog (“Login”) .WinButton (“ok”). Check Checkpoint (“ok”) Draw Backs of Check Checkpoint: - All Checkpoint syntax is same and hence unable to find what kind of Checkpoint it is. Copied checkpoint statement does not run in another script (Action) And hence above are the reasons mostly we are not using any checkpoints, we convert checkpoints scenarios in to VBScript Converting check points to VBScript: If Window (“Flight Reservation”).WinButton (“insert Order”).GetROProperty (“enabled”)=”true” Then Window (“Flight Reservation”).WinButton (“insert Order”).Click Else MsgBox “Insert Order is disabled” 2. Text Checkpoint: -It is used to validate given text in given object With Select Text Checkpoint Check Point Insert Menu Click Record in Qtp Navigation: - Open AUT Select required Click on Configuration Button Click on OK button help of handler Select Required Objet Stop Recording Click on OK Button text
  • 32. Ex: -Window (“notepad”).WinEditor (“Edit”). Check Checkpoint (“Edit”) Converting check points to VBScript: In Notepad: - My name is Sreekar there is no prerequisite for learning QTP please come here and learn QTP validate QTP is exist in notepad sText = Window (“notepad”).WinEditor (“Edit”).GetROProperty (“Text”) If InStr (sText, “qtp”) > 0 Then MsgBox “Text is found” Else MsgBox “Text is Not Found” 3. Text Area Checkpoint: - It is used to validate given text is exist in between given text Select Text Area Check Point Insert Menu Click Record in Qtp Navigation: - Open AUT Stop Recording Click on OK Button Select Checked Text, Check After Text, Checked Before Text click on OK Button Select Required Text Checkpoint Ex: -Window (“notepad”).WinEditor (“Edit”). Check Checkpoint (“Edit”) In Notepad: - My name is Sreekar there is no prerequisite for learning QTP please come here and learn QTP validate QTP is exist in notepad H.W:- Validate Sreekar is existing in Between name and QTP 4. Bitmap Checkpoint: -It is used to compare two images Select Bit Map Check Point Insert Menu Click Record in Qtp Navigation: - Open AUT Minimize or Close expected Stop Recording click on OK Button Select the Expected Image Checkpoint Analyze the Result Run Script Open actual image[which need to Test] Image Scripts related to Standard Checkpoint Check Points Scripts related to Standard Checkpoint: Script No3: - Write a script to validate Calculator Functionalities
  • 33. Script No4: - Write a script for Object Existence [Validation of Vehicle Insurance] Scripts related to Standard Checkpoint Check Points How to get the Menu Options if we are not able to find with Obj Spy? Script: - ********** Write a script to Select MENU Options Method 1: - In Menu Options we cannot identify the objects with Object Spy through Recording we are going to generate the script Window ("Flight Reservation").Activate Window ("Flight Reservation").WinMenu("Menu").Select "File;Open Order..." Window ("Flight Reservation").WinMenu("Menu").Select "Help;About..." Method 2: - Without Recording we get the Menu items by using short cut keys
  • 34. Window ("Flight Reservation").Activate Window ("Flight Reservation").Type micAltDwn + "h" + micAltUP + "a" QTP - Chapter V Scripts related to Standard Checkpoint Check Points Script No12: - Write a Script to find given value is exist in DROP DOWN Example: -kesinenitravels.com validate “HYDERABAD” is exist in from drop down Method 1:- Option Explicit Dim sExpItem,iFlag,iItemCnt,index,sItemName,obj sExpItem = "KURNOOL" iFlag = 0 Set obj = Browser("Kesineni").Page("Kesineni") iItemCnt = obj.WebList("From").GetROProperty("items count") For index = 1 To iItemCnt sItemName = obj.WebList("From").GetItem(index) If sItemName = sExpItem Then Print "Item is Found" iFlag = 1 Exit for ' If we did not declare this the loop will iterate after getting the result also End If Next If iFlag = 0 Then print "Item Not Found" 'if we give it within for loop it iterates, so we took Flag for this End If Limitation: - Above Logic executes for all items if the items are at end or not found Method 2:- On Error Resume Next „It skips the Errors if any occurs in script running time Set obj = Browser("Kesineni").Page("Kesineni") obj.WebList("From").Select sExpItem If Err.Number = 0 Then „Err.Number will give the script run time ERROR NUMBERS it is VB Utill MsgBox "Item is found" Else MsgBox "Item Not Found" End If Limitation: -If item is not found then result window displays with RUNTIME ERROR which we won‟t accept Method 3:- Question: - Write a script for dropdown On Error Resume Next „It skips the Errors if any occurs in script running time Set obj = Browser("Kesineni").Page("Kesineni")
  • 35. sItemName = obj.WebList("From").GetROProperty("all items") If InStr(sItemName, sExpItem) > 0 Then MsgBox "Item is Found" Else MsgBox "Item Not Found" End If Question: - How do you find Combobox or ListBox items? In Windows based application we have “GetItemCount” In Web based application we have “GetROProperty (―item count‖)” Note:-**** 1. Err.Number: - To identify runtime error number 2. On Error Resume Next: - When we get any error in script execution it skips that line goes to next Scripts related to Standard Checkpoint Check Points Script No13: - Write a script for Rail Reservation Set obj = Browser("Reservation").Pabe("Reservation") obj.WebEdit("Name").Set "Sreekar" obj.WebEdit("Age").Set "32" obj.WebList("Gender").Select "Male" obj.WebList("Name").Select "Hyderabad" obj.WebList("Name").Select "Kurnool" 'Validate default Class If obj.WebRadioGroup("Class").GetROProperty("value") = "AC" Then MsgBox "Default Class is AC" Else MsgBox "Default Class is Not AC" End If „Validate Class Price obj.WebRadioGroup("Class").Select "AC" iTcktPrice = obj.WebEdit ("Ticket Price").GetROProperty("text") iTcktPrice = Mid(iTcktPrice,4,Len(iTcktPrice)-5) 'Rs:1000/- If iTcktPrice = "1000" Then MsgBox "AC Price is 1000/-" Else MsgBox "AC Price Not 1000/-"
  • 36. End If obj.WebRadioGroup("Class").Select "Sleeper" iTcktPrice = obj.WebEdit ("Ticket Price").GetROProperty("text") iTcktPrice = Mid(iTcktPrice,4,Len(iTcktPrice)-5) 'Rs:1000/- If iTcktPrice = "1000" Then MsgBox "Sleeper Price is 500/-" Else MsgBox "Sleeper Price Not 500/-" End If 'Validate No of Tickets iTickets = InputBox("Enter number of Tickets") obj.WebEdit("Tickets").Set iTickets obj.WeButton("Submit").Click iTotalPrice = obj.WebEdit("Total Price").GetROProperty("text") iTotalPrice = Mid(iTotalPrice,4,Len(iTotalPrice)-5) If iTotalPrice = iTickets * iTicketPrice Then MsgBox "Total Price Functionality Validation is Pass" Else MsgBox "Total Price Functionality Validation is Fail" End If iTcktNo = obj.WebEdit("TicketNo").GetProperty("text") If NOT IsEmpty (iTcktNo) Then MsgBox "Ticket Noumber Validation is Pass" Else MsgBox "Ticket Noumber Validation is Fail" End If Scripts Related to Text Checkpoint Ex: - Notepad: - my name is sreekar there is no prerequisite for learning QTP please come here and learn QTP Script No5: -Write a script to Validate Text Existence Ex: - Notepad: Validate sreekar text existence:- Option Explicit Dim sActTxt, sExpTxt sExpTxt = "sreekar" sActTxt = Window("Notepad").WinEditor("Edit").GetROProperty ("text") If InStr(sActTxt, sExpTxt) > 0Then MsgBox "Text is Found" Else MsgBox "Text is Not Found" End If Script No6: -Write a script to find the string number of occurrences Ex: - Notepad: Find sreekar text number of occurrence:- Option Explicit Dim sActTxt, sExpTxt sExpTxt = "sreekar"
  • 37. sActTxt = Window("Notepad").WinEditor("Edit").GetROProperty ("text") MsgBox (Len(sActTxt)- Len(Replace(sActTxt,sExpTxt,"")))/ Len(sExpTxt) Script No7: - Write a script to find the ovals Ex: - Notepad: - Option Explicit Dim sActTxt, iACnt,iECnt,iICnt,iOCnt,iUCnt sActTxt = Window("Notepad").WinEditor("Edit").GetROProperty( "text") iACnt = Len(sActTxt)-Len(Replace(sActTxt,"a","")) iECnt = Len(sActTxt)-Len(Replace(sActTxt,"e","")) iICnt = Len(sActTxt)-Len(Replace(sActTxt,"i","")) iOCnt = Len(sActTxt)-Len(Replace(sActTxt,"o","")) iUCnt = Len(sActTxt)-Len(Replace(sActTxt,"u","")) MsgBox iACnt+iECnt+iICnt+iOCnt+iUCnt Script No8: - Write a script to find number of Alphabets Ex: - Notepad: - Option Explicit Dim sActTxt,index,iCnt, iChrCnt iChrCnt = 0 sActTxt = UCase( Window("Notepad").WinEditor("Edit").GetROProperty( "text")) MsgBox Len(sActTxt) For index = 65 To 90 'upper Case A - Z iCnt = Len(sActTxt) - Len(Replace(sActTxt, Chr(index),"")) iChrCnt=iChrCnt + iCnt Next MsgBox iChrCnt Script No9: - Write a script to find number of strings in a given text [&_ for Continue the line] Option Explicit Dim sActTxt,index,iCnt, iChrCnt sActTxt = "my name is sreekar there is no prerequisite for learning QTP"&_ "Please come here and learn QTP" iChrCnt = 0 sActTxt = Split (sActTxt, " ") MsgBox UBound (sActTxt) + 1 Scripts related to Text Area Checkpoint Script No10: -Write a Script to find given text existence in between given two texts Ex: - Notepad:Find sreekar in between name and QTP Script No11: - Write a script to retrieve Driver letter, File Path and File Name from given Text Option Explicit Dim sActTxt,index,iCnt, iChrCnt sActTxt = "D:sreekarbatch40test scriptssamplesample.mts"
  • 38. MsgBox "Driver Letter is: - " & Mid(sActTxt,1,1) MsgBox "File Name is: - " & Mid(sActTxt,InStrRev(sActTxt,"")+1) MsgBox InStrRev(sActTxt,"") MsgBox "File Path is: -" & Mid(sActTxt,4, InStrRev(sActTxt,"")-4) [Here to find the file path we subtracted 4 {1st 3 {D :} letters and last occurrence of ―‖}] CaptureBitMap: - It is used to take a screen for the given object Syntax: - .CaptureBitMap “Path.bmp/png” Ex: - Capture Login Dialog("Login").CaptureBitMap "E:01 My Scriptslogin.bmp" Capture OK button in Login Dialog Dialog("Login").WinButton("OK").CaptureBitMap "E:01 My Scriptsloginokbtn.bmp" Note: - When we capture child object, QTP captures only child Object Capture Desktop Window ("text:= QuickTest.*").Minimize Desktop.CaptureBitmap("E:01 My ScriptsDesktop.bmp") Window("text=QuickTest.*").Maximize [;- Descriptive Programming] Script No14: - Write a script to Right Click on Notepad editor and select past by using down arrow key Set obj = CreateObject ("WScript.Shell") Window("Notepad").Activate iXCord = Window("Notepad").WinEditor("Edit").GetROProperty("x") iYCord = Window("Notepad").WinEditor("Edit").GetROProperty("y") Window("Notepad").Activate Window("Notepad").WinEditor("Edit").Click iXCord, iYCord,micRightBtn obj.SendKeys "{DOWN}" ' These things we can write in Loop Wait(1) obj.SendKeys "{DOWN}" Wait(1) obj.SendKeys "{DOWN}" Wait(1) obj.SendKeys "{DOWN}" obj.SendKeys"{ENTER}" For index= 1 To 4 obj.SendKeys "{DOWN}" wait(1) Next Script No15: - Write a script to open an existing notepad right click on it, select ―Select All ―option by pressing/ Sending UP arrow key (in windows 7 it differs) one time, Right Click on Notepad, select copy option by sending Down arrow key for 3 (in windows 7 it differs) times, close the notepad, open a new notepad, Right Click on it select past by sending UP arrow key for 3(in windows 7 it differs) times. SystemUtil.Run "E:01 My Scripts1.txt" Set obj = CreateObject("WScript.Shell") 'Window("Notepad").Activate
  • 39. iXCord = Window("Notepad").WinEditor("Edit").GetROProperty("x") iYCord = Window("Notepad").WinEditor("Edit").GetROProperty("y") 'Window("Notepad").Activate Window("Notepad").WinEditor("Edit").Click iXCord, iYCord,micRightBtn For index = 1 To 6 obj.SendKeys"{UP}" 'Wait(1) Next obj.SendKeys"{ENTER}" 'Wait(1) Window("Notepad").WinEditor("Edit").Click iXCord, iYCord,micRightBtn For index1 = 1 To 3 obj.SendKeys"{DOWN}" 'Wait(1) Next obj.SendKeys"{ENTER}" Window("Notepad").Close SystemUtil.Run"Notepad" Window("Notepad").WinEditor("Edit").Click iXCord,iYCord,micRightBtn For index2 = 1 To 4 obj.SendKeys"{DOWN}" 'Wait(1) Next obj.SendKeys "{ENTER}" Text Area Checkpoint - Desktop Check Points Script No16: -Write a script to right click on Desktop, select Properties and validate “DESKTOP” Tab Existence in “Display Properties Dialog” if exist then select it. Option Explicit Dim sExpTab,iFlag,sActTab,index,obj,iXCord,iYCord,iTabCnt sExpTab = "Desktop" iFlag = 0 Set obj = CreateObject("WScript.Shell") iXCord = Window("Program Manager").WinListView("SysListView32").GetROProperty("x") iYCord = Window("Program Manager").WinListView("SysListView32").GetROProperty("y") Window("text:=QuickTest.*").Minimize Window("Program Manager").WinListView("SysListView32").Click iXCord,iYCord,micRightBtn Wait(1) obj.SendKeys"{UP}" obj.SendKeys"{ENTER}" iTabCnt = Dialog("Display Properties").WinTab("SysTabControl32").GetItemsCount For index = 0 To iTabCnt-1 sActTab = Dialog("Display Properties").WinTab("SysTabControl32").GetItem(index) If sExpTab = sActTab Then iFlag = 1 Dialog("Display Properties").WinTab("SysTabControl32").Select sExpTab MsgBox "Given Tab is Found and Selected" Exit For End If Next If iFlag = 0 Then
  • 40. MsgBox"Given Tab is Not Found" End If QTP - Chapter VI Chapter VI Working with Test Result We display test results in Test Result window by using Reporter Utility Object We display bellow Types of results: 1. Pass 2. Fail 3. Warning 4. Normal Syntax: - Report.ReportEvent,””,”” We have 4 types of event status 1. micPass (0) 2. micFail (1) 3. micWarning (3) 4. micDone [Normal] (2) Ex: - Reporter.Reportevent micPass, “Validate dialog login exist”,”Dialog login exist” Reporter.Reportevent micFail, “Validate dialog login exist”,”Dialog login not exist” Reporter.Reportevent micWarning, “Validate dialog login exist”,”Dialog login is minimized” Reporter.Reportevent micDone, “execution start”, “Test script execution start” Ex: - If Dialog (“login”).exist=”True” Then Reporter.Reportevent micPass, “Validate dialog login exist”, “Dialog login exist” Else Reporter.Reportevent micFail, “Validate dialog login exist”, “Dialog login not exist” Endif Save text Results in Required Path: - Navigation: - Click Run Button->Select new Run Results folder Radio button->Click Browser->Browse and open required path->Click OK button.->After script execution QTP saved a given folder in given path. QTP - Chapter VII - VIII - IX Utility Objects -->These are predefined by QTP which are used to enhancing scripting Navigation: Insert Menu ->Step Generator -->Select Category as Utility Objects --> Find List of objects in Objects Drop Down Utility Objects: - Navigation: - Insert Menu -->Stepgenerator -->Select Category as Utility Object -->Find List of Utility Objects in object drop down Crypt: - It encrypts the given script generally it is used to enter Secure Password
  • 41. Eg: - Crypt.Encrypt (“mercury”) [:- object. method] --> We can also encrypt the given string with bellow navigation Start --> all programs -->QTP-->Tools -->Password Encoder-->Enter the String -->Click Generate Button-->click Copy Button -->Paste it where needed. Desktop: - It is used to work with desktop ***Note: -To click the radio button [Ex: - winRadioButton (“”).Set] ***Note: - To check the CheckBox we “ON”, “OFF” [Set “ON”/”OFF”] To know whether CheckBox is checked are not go to spy check the Checked value as ON / OFF and assign the value to GetROProperty RandomNumber: - It is used to generate random number with given range Example: - 1. Generate 4 digit random number MsgBox RandomNumber (1000.9999) 2. Generate 5 Characters String For index = 1 To 5 sStr = sStr & Chr(RandomNumber(65,90)) Next MsgBox sStr SystemUtil: - By using this we open and close application and its process during runtime Run: -It is used to open application during runtime Ex: - Open login Dialog SystemUtil.Run "C:Program FilesHPQuickTest Professionalsamplesflightappflight4a.exe" 'Open internet explore SystemUtil.Run "iexplore" 'Open internet explorer with URL SystemUtil.Run "iexplore", "www.google.com" 'Open EXCEL SystemUtil.Run "EXCEL" 'Open MS Word SystemUtil.Run "WinWord" CloseDescendentProcesses: - It closes all applications which are opened by QTP Ex: -SystemUtil. CloseDescendentProcesses CloseProcessByName: - It closes the given Process Name Ex: -SystemUtil. CloseProcessByName ("EXCEL.EXE")
  • 42. Synchronization -->It is a process of matching the execution speeds for both application and QTP We can implement Synchronization in 4 ways 1. Wait() function 2. WaitProperty Method 3. Increase/ Decrease default time Setting 4. VB Scripting ** 1. Wait Function: --->By using this function we can make to QTP wait in given time in seconds -->It‟s a static way Limitations: - If given time is more than actual application time QTP still to wait, hence we have a performance issue. If given time is less than actual application time than QTP does not wait and continues to next step execution, hence we will get invalid results. Syntax: - Wait (Time in Seconds) Ex: - Wait (30) 2. WaitProperty Method: - ->By using this we can apply synchronization on required object. To wait QTP for given time in milliseconds. Syntax: - 3. Increase/ Decrease default Time Setting: - -->When ever QTP not able to perform any statement then it will wait up to given default time. Navigation: - File -->Setting -->Run -->Increase/ Decrease default time in object Synchronization time out field in seconds. 4. VB Script: - *** Example: - Obj. WinButton (“Insert Order”).Click While obj. WinButton (―Update Order‖).GetROProperty (―enabled‖) = ―False‖ Wend iOrdNo = obj.WinEdit (“Order No”). GetROProperty (“text”) MsgBox iOrdNo [To know the execution time of use MercuryTimers in Utility Objects] Example: -For Synchronization {for this we need Flight Reservation Application} Chapter IX Parameterization Parameterization: - It is a process of replacing static values with dynamic values and executing test scripts with multiple test data is called as parameterization. --> We maintain test data and passing it to UT through QTP in bellow ways. 1. Data Table 2. Environment Variable 3. External Files [Ms-Excel, Notepad, Ms-Word, XML] 4. Action Parameters QTP - Chapter X - XI Data Table Parametrization Chapter X Implementing parametrization by using Data Table Data Table: - It is used to hold the Test Date
  • 43. Navigation: - Data Table View Menu --> It is looks like MS-Excel Spread Sheet --> It contains 65536 Rows and 256 Columns --> By default it contains Global and Action1 Sheet --> Every action of the scripts contains the same sheet in the Data Table Types of Data Table: - 1. Design Data Table 2. Run Time Data Table Design Data Table: - Table which is displaying in test pane is called as Design Data Table Run Time Data Table: - The table which is displaying result window called as Runtime Data Table Note: - Run time Data Table is copy of Design Data Table Note: - Any modifications to data table during runtime it performs the operations in Run Time Data Table not in Design Data Table Note: -Test script execution iterations depends on Global Sheet number of Rows Example: - Global Action1 Action No. of Iterations - - - 1 - 5 10 1 5 10 15 5 10 5 1 10 Rename the column Names of Data Table: - Navigation: - Select the required sheet Design Data Table -->Double click on required column -->Enter new column name -->Click OK Button. By Scripting: - Syntax: - DataTable.GetSheet (“”).AddParameter””, “” Example: - Adding User_Name Column in Global Sheet DataTable.GetSheet(“Global”).AddParameter”User_Name”,”Sreekar” Example: - Adding Val1 Column in Action1 Sheet DataTable.GetSheet(“Action1”).AddParameter”Val1”,”Sreekar” ScriptNo17: - Write a script to find given sheet existence in data table sExpSht = "Action" iFlag = 0 iShtCnt = DataTable.GetSheetCount 'MsgBox iShtCnt For index = 1 To iShtCnt sActSht = DataTable.GetSheet(index).Name If sExpSht = sActSht Then Print "Sheet is Found" iFlag = 1 Exit For End If Next If iFlag = 0 Then Print "Sheet is not Found" End If
  • 44. Retrieving data From Data Table: - --> It retrieves from Run Time Data Table not from Design Table 1. MsgBox DataTable("User_Name") MsgBox DataTable("User_Name",1) MsgBox DataTable("User_Name","Global") MsgBox DataTable. Value("User_Name",1) -->It retrieves User_Name Column value from Global Sheet 2. MsgBox DataTable("User_Name","Action1") -->It retries User_Name Column Value from Action1 Sheet 3. MsgBox DataTable.GetSheet("Global").GetParameter("User_Name").ValueByRow(4) -->It retrieves 4th of User_Name column value from Global Sheet 4. MsgBox DataTable.GetSheet("Action1").GetParameter("User_Name").ValueByRow(4) -->It retrieves 4th row of User_Name column value from Action1 Sheet Entering Data into Data Table: - 1. DataTable("val","Global")="QTP" It Enters "QTP" in val column of Global Sheet 2. DataTable("val","Action1")="QTP" It Enters "QTP" in val column of Action1 Sheet 3. DataTable.GetSheet("Global").GetParameter("val").ValueByRow(3)="QTP" It Enters "QTP" in 3rd Row of val column in Global Sheet 4. DataTable.GetSheet("Action1").GetParameter("val").ValueByRow(3)="QTP" It Enters "QTP" in 3rd Row of val column in Action1Sheet Methods for Data Table: -By using this method we can perform required operations to the Run Time Data Table 1. AddSheet: - It is used to add a required sheet to the Run time Data Table (RDT) Syntax: - DataTable. AddSheet””
  • 45. Ex: - DataTable.AddSheet"MySheet" -->If we have data in multiple rows in Global Sheet then it over rights the sheet do not creates new sheet like MYSheet1 2. DeleteSheet: - It is used to Delete a required sheet from RDT Syntax: - DataTable. DeleteSheet"" Ex: DataTable.DeleteSheet"Global" DataTable.AddSheet"MySheet" DataTable.DeleteSheet"Action1" -->At least one is default in Data Table 3. Export: - It is used to save a RDT in given path Syntax: - DataTable.Export”Path” Ex: - DataTable.Export"E:01 My Scriptstest.xls" 4. ExportSheet: - It is used to Save a required sheet of RDT in required path Syntax: - DataTable.ExportSheet"Path",”” Ex: DataTable.AddSheet"MySheet" DataTable.GetSheet("MySheet").AddParameter"User_Name","Sreekar" DataTable.ExportSheet"E:01 My Scriptstest.xls","MySheet" 5. GetCurrentRow: - It is used to retrieve the current Active Row from the required sheet of RDT. Ex: - --> Retrieving from Global Sheet MsgBox DataTable.GetCurrentRow (or) MsgBox DataTable.GetSheet("Global").GetCurrentRow Retrieving from Action1 Sheet MsgBox DataTable.GetSheet("Action1").GetCurrentRow 6. GetRowCount: - By using this we can retrieve number of rows from required sheet of RDT Ex: -->Retrieving from Global Sheet MsgBox DataTable.GetRowCount (or) MsgBox DataTable.GetSheet("Global").GetRowCount -->Retrieving from Action1 Sheet MsgBox DataTable.GetSheet("Action1").GetRowCount 7. GetSheet: - It is used to Activate required sheet from RDT Syntax: - DataTable.GetSheet("") Example: -DataTable.GetSheet("Global") DataTable.GetSheet("Action1") 8. GetSheetCount: - It is used to retrieve number of sheets from RDT Ex: - MsgBox DataTable.GetSheetCount 9. Import: - It is used to save a excel file in RDT [How many sheets we have in RDT it imports only that number of sheets from Excel] Ex: - DataTable.AddSheet"MySheet" DataTable.Import"E:01 My Scriptstest.xls"
  • 46. 10. ImportSheet: - It is used to save a required sheet of MS-Excel to required sheet of RDT Syntax: - DataTable.ImportSheet”Path”,Ms-Excle Sheet ID, RDT Sheet ID Ex: - DataTable.ImportSheet"E:01 My Scriptstest.xls",3,2 11. SetCurrentRow: - It is used to activate required row in required sheet of RDT Ex: - -->Activating row in Global Sheet DataTable.SetCurrentRow(1) [or] DataTable.GetSheet ("Global").SetCurrentRow(2) -->Activating row in Action1Sheet DataTable.GetSheet ("Action1").SetCurrentRow(2) 12. SetNextRow: - It activates the Next row of current active row Ex: ---> Activating Global Sheet DataTable. SetNextRow (or) DataTable.GetSheet("Global").SetNextRow -->Activating Action1 Sheet DataTable.GetSheet("Action1").SetNextRow 13. SetPrevRow: -It activates previous row of current active row Ex: - -->Activating Global Sheet DataTable. SetPrevRow DataTable.GetSheet("Global").SetPrevRow -->Activating Action1 Sheet DataTable.GetSheet("Action1").SetPrevRow Ex: - MsgBox DataTable. GetCurrentRow DataTable.GetSheet ("Action1").SetPrevRow DataTable ("val1","Action1") ScriptNo18: - Write a script to find mathematical operation to given values, maintain data in Excel File. On Error Resume Next Dim iRowCnt,iRowNum,iVal1,iVal2 DataTable.ImportSheet"E:01 My Scriptscal.xls", 1, 2 iRowCnt = DataTable.GetSheet("Action1").GetRowCount For iRowNum = 1 To iRowCnt iVal1 = CInt (DataTable("val1","Action1")) iVal2 = CInt (DataTable("val2","Action1")) DataTable("add","Action1") = iVal1 + iVal2 DataTable("sub","Action1") = iVal1 - iVal2 DataTable("mul","Action1") = iVal1 * iVal2 DataTable("div","Action1") = iVal1 / iVal2
  • 47. If Err.Number <> 0 Then DataTable("comments","Action1") = Err.Description Err.Clear End If DataTable.GetSheet("Action1").SetNextRow Next DataTable.Export"E:01 My Scriptscalresult.xls" ScriptNo19: - Write a script for Login functionality for Multiple Users -->Maintain DATA in MS-Excel DataTable.ImportSheet"E:01 My Scriptsdatatable-user.xls",1,2 iRowCnt = DataTable.GetSheet("Action1").GetRowCount For i = 1 To iRowCnt sUname = DataTable("Username","Action1") sPwd = DataTable("Password","Action1") SystemUtil.Run "C:Program FilesHPQuickTest Professionalsamplesflightappflight4a.exe" If Dialog("Login").Exist Then Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set sUname Dialog("Login").WinEdit("Password:").Set sPwd Dialog("Login").WinButton("OK").Click If Dialog("Login").Dialog("Flight Reservations").Exist(5) Then Dialog("Login").Dialog("Flight Reservations").Activate sError = Dialog("Login").Dialog("Flight Reservations").Static("Please enter agent name").GetROProperty("text") Dialog("Login").Dialog("Flight Reservations").Close Dialog("Login").Close DataTable("Results","Action1") = sError Else If Window("Flight Reservation").Exist Then DataTable("Results","Action1") = "Valid User" Window("Flight Reservation").Activate Window("Flight Reservation").Close Else DataTable("Results","Action1") = "User is valid but not opened the application" End If End If Else DataTable("Results","Action1") = "Application not Oppened"
  • 48. End If DataTable.GetSheet("Action1").SetNextRow Next DataTable.Export"E:01 My Scriptsdatatable-user1.xls" ScriptNo20: - Write a script to retrieve Fly From dropdown values [Maintain in Excel] ScriptNo21: - Write a script to import Val1 values from sample1.xls file and import Val2 values from sample2.xls file, perform the mathematical operations and write the result in results.xls file QTP - Chapter XI Parameterization Environment Variable Implementing parameterization by using Environment Variable By using Environment Variables we can share the variable values in multiple actions (or) multiple scripts Types of Environment Variables: - 1. Built-In Environment Variables 2. User Defined Internal Environment Variables 3. User Defined External Environment Variables Built-In: - These are Pre-Defined by QTP Navigation: - Select Variable Type as Built-In Environment Setting File Menu Ex: - ActionName: Retrieves current action name ResultDir: Retrieves Test Script execution Result Path TestName: Retrieves Current Test Script Name MsgBox Environment ("ActionName") MsgBox Environment ("ResultDir") MsgBox Environment ("TestName") Note 1: - Built-In Environment variables are Read-Only Note 2: - Environment Variables are case sensitive User Defined Internal: - Declaring and using in same test scripts are called as User Defined Internal Environment Variables Navigation: - File Menu-->Environment Setting-->Select Variable Type as User Defined-->Click on ADD[+] Button Enter name and Value-->Click OK button -->Click Apply and OK Note: - Internal Environment variables are not Read-Only we can modify data at run time. Syntax: - Environment(“”) = “” Environment(“iVal”) = 10
  • 49. User Defined External: - Creating external Environment Variables: - Method 1: By Navigation: - File Menu-->Setting-->Environment-->Select Variable Type as User Defined-->Click on ADD [+] Button Enter Name and Value-->click on OK button-->click Export Button-->Save the file in required path with “.XML” extension Method 2: Open NOTEPAD and declare the variables as follows sPassword mercury sUserName suresh Associating External Environment Variable File:- Method 1: Navigation: - File Menu-->Setting-->Environment-->Select Variable Type as User Defined-->Click on Load Variables and Values from Eternal File Check Box-->Browse XML file-->Click Apply and OK buttons Method 2: - Syntax: - Environment.LoadFromFile”File Path” Environment.LoadFromFile "E:01 My Scriptsexternal EV.xml" Note: - We can associate only one XML file by navigation OR by scripting if we associate 2nd file then first file will be replaced with second file. Note: - User Defined External Environment Variable are Read Only.. QTP - Chapter XII External File [Excel] Parameterization Implementing parameterization by using External File External files are the files where we maintain the data outside of QTP, like ms-Excel, Notepad, Ms-Word, XML… Working with MS-EXCEL Creating Excel Object: - Set objXL = CreateObject("Excel.Application") Creating Work Book Object: - Set objWrkBk = objXL.Workbooks.Add Open an Existing Work Book: - Set objWrkBk = objXL.Workbooks.Open("E:01 My Scriptsexternal EV.xml") Creating a Work Sheet Object: - Set objWrkSht = objWrkBk.Worksheets("Sheet1") 'Activating the Sheet Find the No. of Rows: - MsgBox objWrkSht.UsedRange.Rows.Count Find the No. of Columns:- MsgBox objWrkSht.UsedRange.Columns.Count Retrieving a required Cell Value: - MsgBox objWrkSht.Cell(3,2) Entering data to Cell: - objWrkSht.Cell(14,8) = "QTP" Save opened Work Book: - objWrkBk.Save Save the New Work Book: - objWrkBk.SaveAs"Path" Close the Work Book: - objWrkBk.Close Close Excel: - objXL.Quit Kill Excel Process: - Set objWrkSht = Nothing
  • 50. Set objWrkBk = Nothing Set objXL = Nothing External File [Excel] ScriptNo22: - Write a script to create orders maintain data in Excel file 'Option Explicit 'Dim objXL,objWrkBk,objWrkSht,iRowCnt Set objXL = CreateObject("Excel.Application") Set objWrkBk = objXL.Workbooks.Open("E:01 My ScriptsExcel.xls") Set objWrkSht = objWrkBk.Worksheets("Sheet1") iRowCnt = objWrkSht.UsedRange.Rows.Count Set obj = Window("Flight Reservation") For index = 2 To iRowCnt obj.Activate obj.WinMenu("Menu").Select "File;New Order" dDate = objWrkSht.Cells(index,1) '(Row,Column) obj.WinObject("Date of Flight:").Type dDate sFrom = objWrkSht.Cells(index,2) obj.WinComboBox("Fly From:").Select sFrom sTo = objWrkSht.Cells(index,3) obj.WinComboBox("Fly To:").Select sTo obj.WinButton("FLIGHT").Click obj.Dialog("Flights Table").WinList("From").Select(0) obj.Dialog("Flights Table").WinButton("OK").Click sName = objWrkSht.Cells(index,4) obj.WinEdit("Name:").Set sName sCls = objWrkSht.Cells(index,5) obj.WinRadioButton(sCls).Set iTckts = objWrkSht.Cells(index,6) obj.WinEdit("Tickets:").Set iTckts obj.WinButton("Insert Order").Click While obj.WinButton("Update Order").GetROProperty("Enabled") = "False" Wend iOrdNo = obj.WinEdit("Order No:").GetROProperty("Text") If IsEmpty(iOrdNo) = "False" Then objWrkSht.Cells(index,7) = obj.WinEdit("Price:").GetROProperty("Text") objWrkSht.Cells(index,8) = obj.WinEdit("Total:").GetROProperty("Text") objWrkSht.Cells(index,9) = obj.WinEdit("Order No:").GetROProperty("Text") objWrkSht.Cells(index,10) = "Order is Generated"
  • 51. Else objWrkSht.Cells(index,10) = "Order is Not Generated" End If Next objWrkBk.Save objWrkBk.Close objXL.Quit Set objWrkSht = Nothing Set objWrkBk = Nothing Set objXL = Nothing Renaming a Sheet Name: - Set objXL = CreateObject ("Excel.Application") Set objWrkBk = objXL.Workbooks.Open("E:01 My ScriptsExcel1.xlsx") Set objWrkSht = objWrkBk.Worksheets("Sheet2") objWrkSht.Name = "User_Data1" Add a New sheet to Workbook: - objWrkBk.Sheets.Add Delete an Existence Sheet: - objWrkBk.Sheets("Sheet3").Select objXL.ActiveWindow.SelectedSheets.Delete Auto fit for require Column in Active Sheet: - objWrkSht.Columns("D:D").EntireColumn.AutoFit Wrap Text {Format Column}: - 'objWrkSht.Columns("A1:D1").HorizontalAlignment = xlGeneral 'objWrkSht.Columns("A1:D1").VerticalAlignment = xlTop objWrkSht.Columns("A1:D1").WrapText = True Bold and Color to one Cell: - objWrkSht.Cells(8,8).Font.Bold = True objWrkSht.Cells(8,8).Font.Color = vbRed objWrkSht.Cells(8,8) = "Suresh" objWrkSht.Cells(8,8).Interior.ColorIndex = 55 ScriptNo23: - Write a script to retrieve val1 values from sheet1, retrieve val2 values from sheet2 and perform mathematical operation and retrieve the results in sheet3
  • 52. Working with NOTEPAD Creating notepad Object: - Set objFile = CreateObject ("Scripting.FileSystemObject") Creating Notepad Pointer: - Syntax: -Set objPtr = objFile. OpenTextFile (“Path of Notepad”,Mode[,True]) Set objPtr = objFile. OpenTextFile ("E:01 My Scripts1.txt",1) Retrieving Value from notepad: - Retrieving a Line: objPtr.ReadLine Retrieving all Values: objPtr.ReadAll Retrieving One by One on till end of Line: While objPtr.AtEndOfLine = "False" MsgBox objPtr.SkipLine 'Even MsgBox objPtr.ReadLine MsgBox objPtr.SkipLine 'Odd Wend Retrieving given Line value: -
  • 53. Set objFile = CreateObject ("Scripting.FileSystemObject") Set objPtr = objFile. OpenTextFile ("E:01 My Scripts1.txt",1) iLine = 1 iFlag = 0 While objPtr.AtEndOfLine = "False" If iLine = 5 Then MsgBox objPtr.ReadLine iFlag = 1 Else ival1 = objPtr.ReadLine End If iLine = iLine + 1 Wend If iFlag= 0 Then MsgBox "Line number not found" End If Entering the Data/values into notepad: - Set objFile = CreateObject("Scripting.fileSystemObject") Set objPtr = objFile.OpenTextFile("E:01 My Scripts2.txt",2,True ) objPtr.write "Suresh" objPtr.WriteLine "Sreekar" objPtr.WriteLine"Prsad" objPtr.WriteLine "Srilatha" objPtr.Write "Sushma" objPtr.WriteLine"Subashini" objPtr.Write"Sandeep" objPtr.Write"Sanjay" Notepad Object Method: - 1. CopyFile 2. CopyFolder 3. CreateFolder 4. CreateTextFile 5. DeleteFile 6. DeleteFolder 7. FileExists 8. FolderExists 9. OpenTextFile CopyFile: - Copy one file content to another file of same file types Syntax: - objFile.CopyFile"path of source file","path of destination file" Ex: - objFile.CopyFile" D:sample1.txt ","D: sample2.txt" CopyFolder: - Copy one file content to another file of same file types Syntax: - objFile.CopyFolder"path of source file","path of destination file" CreateFolder: - It is used to create a required folder in required path Syntax: -objFile.CreateFolder”path” Ex: - objFile.CreateFolder”d:test datasample” Creating a Folder with Current System data & time: Set objFile = CreateObject("Scripting.FileSystemObject")
  • 54. iFoldername = Now iFoldername = Replace(iFoldername,"/","_") iFoldername = Replace(iFoldername,":","_") objFile.CreateFolder "E:01 My Scripts"&iFoldername CreateTextFile: - By using this method we can create new Notepad File Ex: - Set objFile = CreateObject("Scripting.fileSystemObject") objFile.CreateTextFile("E:01 My ScriptsSample3.txt") DeleteFile: - Used to delete existing file DeleteFolder: - Used to delete existing Folder FileExists: - By using this method we can find file exist: It returns True if file exist It returns False if file exist Ex: - MsgBox objFile.FileExists("E:01 My ScriptsSample3.txt") FolderExists: - By using this method we can find Folder exist: It returns True if file exist It returns False if file exist Ex: - MsgBox objFile.FolderExists("E:01 My Scripts") OpenTextFile: - It is used to open exist text file for read/write/ append Ex: - Set objPtr = objFile.OpenTextFile("E:01 My Scripts2.txt",2) ScriptNo24: - Write a script to copy sample excel data into Notepad Set objFile = CreateObject("Scripting.fileSystemObject") Set objPtr = objFile.OpenTextFile("E:01 My Scripts3.txt",2,True) Set objXl = CreateObject("Excel.Application") Set objWrkBk = objXl.Workbooks.Open("E:01 My ScriptsExp.xlsx") Set objWrkSht = objWrkBk.Worksheets("Sheet1") iRowCnt = objWrkSht.UsedRange.Rows.Count For iRowNum = 2 To iRowCnt sName = objWrkSht.Cells(iRowNum,1) iExperience = objWrkSht.Cells(iRowNum,2) sIndustry = objWrkSht.Cells(iRowNum,3) objPtr.WriteLine sName&" has "&iExperience&" Years of Experience in "&sIndustry&" industry” Next objWrkBk.Close Set objWrkSht = Nothing Set objWrkBk = Nothing Set objXl = Nothing Set objPtr = Nothing Set objFile = Nothing ScriptNo25: - Write a script for Fax Order; maintain fax numbers in notepad file Set objFile = CreateObject("Scripting.FileSystemObject") Set objPtr1 = objFile.OpenTextFile("E:01 My Scripts2.txt",1) Set objPtr2 = objFile.OpenTextFile("E:01 My Scripts4.txt",2,True) Set obj = Window("Flight Reservation") While objPtr1.AtEndOfLine = "False" sStr = objPtr1.ReadLine
  • 55. sString = Split(sStr," ") iOrderNo = sString(3) iFaxNo = sString(8) 'MsgBox iOrderNo &" " &iFaxNo obj.Activate obj.WinMenu("Menu").Select "File;Open Order..." obj.Dialog("Open Order").WinCheckBox("Order No.").Set "ON" obj.Dialog("Open Order").WinEdit("Edit_2").Set iOrderNo obj.Dialog("Open Order").WinButton("OK").Click If obj.Dialog("Open Order").Dialog("Flight Reservations").Exist(4) Then obj.Dialog("Open Order").Dialog("Flight Reservations").WinButton("OK").Click obj.Dialog("Open Order").WinButton("Cancel").Click objPtr2.WriteLine iOrderNo &"Order is not found and hence unable to send Fax" Else obj.Activate obj.WinMenu("Menu").Select "File;Fax Order..." obj.Dialog("Fax Order No. 1").WinObject("Fax Number:").Type iFaxNo obj.Window("Fax Order No. 1").RunAnalog "Track1" obj.Dialog("Fax Order No. 1").WinButton("Send").Click If obj.Dialog("Fax Order No. 1").Dialog("Flight Reservations").Exist(4) Then obj.Dialog("Fax Order No. 1").Dialog("Flight Reservations").WinButton("OK").Click obj.Dialog("Fax Order No. 1").WinButton("Cancel").Click objPtr2.WriteLine "Invalid Fax Number" &iFaxNo& "For the Order" &iOrderNo Else While obj.Dialog("Fax Order No. 1").Exist(2) = True Wend sFaxMsg = obj.WinObject("Fax Sent Successfully...").GetROProperty("Text") If sFaxMsg = "Fax Sent Successfully..." Then objPtr2.WriteLine "Fax Sent Success Fully for the order " &iOrderNo Else objPtr2.WriteLine "Fax Sent Success Fully for the order " &iOrderNo End If End If End If Wend Note: - Generally we use Notepad for maintaining DATABASE queries Note: - For general maintaining data like UserName, Password…etc we use excel files Working with Ms-Word Set objWrd = CreateObject(“Word.Application”) Creating XML object
  • 56. Set objXML = CreateObject(“XML.Application”) Implementing parameterization by using Action Parameters -->Actions are used to divide test script in to logically related groups of QTP statements. -->Actions are used to script maintainability and script re-usability. --> We use actions when functional testers maintain scenario based test scripts. That is one scenario containing multiple test cases. Ex: - Scenario -->Every script we have “default action”, it is Action1 -->Every action of script will have sheet in data table and sheet name will be same as Action name. Creating a New Action: - Method-1:- By Navigation: - Click OK Button Enter Action Name Call to New Action Insert Menu Method-2:- Run Time: - Set objQtp = CreateObject(“QuickTest.Application”) objQtp.Test.AddNewAction””,””,” Content>”,””,”” Ex: - objQtp.Test.AddNewAction “sample”,”test”,”test”, 1, 1 ScriptNo26: - Write a script to create multiple Actions and prove that we can create only 255 actions
  • 57. QTP - Chapter XIII Re-Naming: - Select the required Action-->Right Click on Test Pane-->Actions-->Action Properties-->Re-Name the Action Name-->Click OK button. Deleting an Action: - Navigation1: -Select the required action-->Edit Menu-->Action-->Delete Action-->Click Yes Button in Conformation message. Navigation2: - Keyword view -->Right Click on required Action-->Select Delete-->Click Yes Button in conformation message. ScriptNo27: - Write a script to find given Action Existence sExpAction = "Action5" iFlag = 0 Set objQtp = CreateObject("QuickTest.Application") iActionCnt = objQtp.Test.Actions.Count MsgBox iActionCnt For index = 1 to iActionCnt Print objQtp.Test.Actions(index).Name If objQtp.Test.Actions (index).Name = sExpAction Then MsgBox "Action is Found" iFlag = 1 Exit for End If Next If iFlag = 0 Then MsgBox "Action is Not Found" End If Set objQtp = Nothing -->By default actions are executing in order which we are created. -->If we want to change the order of action execution then we follow bellow navigation Navigation: - Select the required action and drag and drop in required position Keyword View Types of Actions: - 1. Normal /Non Reusable Action
  • 58. 2. Re- Usable Actions 3. External Re-Usable Actions Normal /Non Reusable Action: - An Action that can be called only in the test without reusability called as Normal /Non Reusable Action. Re- Usable Actions: - An Action that can be called in same test script and in another test script multiple times is called as Re- Usable Actions. External Re-Usable Actions: - An Action that can be call in same test script or in another test script in multiple times in READ ONLY mode are called as External Re-Usable Actions Implement Script Reusability by Action: - We can implement a Script Reusability by Action, in bellow ways 1. Call to Copy of Action 2. Call to Existing Action Calling Action: - The Action which is calling another action Called Action: - The Action which is called by another Action Implementing re usability by using Call to Copy: - Navigation: - Open calling test script -->insert Menu --> select call to copy of action -->browse the required called to test script -->select the required action --> click on OK button Syntax: - RunAction”Copy of ”, OneIteration Ex: - RunAction “Copy of login”, OneIteration RunAction “Copy of logout”, OneIteration Implementing re usability by using Call to Existing: - Navigation: - Open calling test script --> nsert Menu --> select call to Existing action-->browse the required called test script-->select the required action --> click on OK button Syntax: - RunAction “[Called Test Script]”, OneIteration Ex: - RunAction “login[Action Demo]”, OneIteration RunAction “logout[Action Demo]”, OneIteration Difference between call to Copy and Call to Existing: - Implementing Parameterization by using Action Parameters
  • 59. Action Parameters: - These are used to retrieving the data and sending results in between Called Action and Calling Action parameters. There are two types of action parameters 1. Input Parameters: - These are used to retrieving the data from Calling Action to Called Action 2. Output Parameters: - These are used to sending Test Result from Called Action to Calling Action Note: - We create Action Parameters in Called Action. Note: - Action Parameters are independent to Action Navigation to create Action Parameters: - Open Called test script-->select the required action right click on test pane-->select Action-->Action Properties-->select Parameter Tab-->Click Add button-->Enter parameter name and value-->Click on OK button. Split of Action: - Right click on required statement-->select Action-->Split-->Enter First Action Name--> Enter Second Action Name-->Click on OK button ScriptNo28: - Write a script for login logout by using Action Parameter Concept -->Open called Test Script and create 2 actions login and logout -->Enter bellow code -->Create sUname, sPwd input parameters and sRslt as output parameters Script Name [loginlogout]-Action Name [Login]: - [Add Action Parameters (sUName, sPwd, sRslt) to loginlogout script] SystemUtil.Run "C:Program FilesHPQuickTest Professionalsamplesflightappflight4a.exe" If Dialog("Login").Exist Then Dialog("Login").Activate Dialog("Login").WinEdit("Agent Name:").Set Parameter("sUName") Wait(2) Dialog("Login").WinEdit("Password:").Set Parameter("sPwd") Dialog("Login").WinButton("OK").Click If Dialog("Login").Dialog("Flight Reservations").Exist(5) Then Reporter.ReportEvent micFail,"Login Validation","Given Data is Invalid" Parameter("sRslt") = "Fail" Dialog("Login").Dialog("Flight Reservations").WinButton("OK").Click Dialog("Login").WinButton("Cancel").Click Else If Window("Flight Reservation").Exist Then Reporter.ReportEvent micPass, "Login Validation","Login Validation is Pass" Parameter("sRslt") = "Pass" Window("Flight Reservation").Close Else Reporter.ReportEvent micFail, "Login Validation","Login Validation is Fail" Parameter("sRslt") = "Fail" End If End If End If
  • 60. Action Name [Logout]: - If Window("Flight Reservation").Exist(5) Then Window("Flight Reservation").Close While Window("Flight Reservation").Exist(2) = True Wend If Window("Flight Reservation").Exist(2) = "False" Then Reporter.ReportEvent micPass, "Close Application","Application is Closed" Else Reporter.ReportEvent micFail,"Close Application","Application is not Closed" End If End If [Here loginlogout script is called actions] Script Name [calngaction]: - this action is calling action Action Template: - It explains Action description as bellow ********************************************************************************* ACtion name: Action Description: Design Date: Tool Used: Comments: ********************************************************************************* Navigation: - Open notepad enter the action template save the file as “ActionTemplate.mst” [MST: -mercury scenario test script] in bellow path save it C:Program filesHPQuick Test Professionaldat
  • 61. Split of Action: - Right click on required statement-->select Action-->Enter First Action Name Split--> Enter Second Action Name-->Click on OK button ScriptNo29: -HW ActionDemo: - Action1 'MsgBox "Login" SystemUtil.Run "C:Program Files (x86)HPQuickTest Professionalsamplesflightappflight4a.exe" If Dialog("Login").Exist Then Dialog("Login").Activate 'Msgbox Parameter("suname") 'MsgBox Parameter("spwd") Dialog("Login").WinEdit("Agent Name:").Set parameter("suname") Dialog("Login").WinEdit("Password:").Set Parameter("spwd") Dialog("Login").WinButton("OK").Click If Dialog("Login").Dialog("Flight Reservations").Exist(3) Then Reporter.ReportEvent micFail, "Login Validation", "Invalid credentials " Parameter("srslt") = "Fail" Dialog("Login").Dialog("Flight Reservations").WinButton("OK").Click Dialog("Login").WinButton("Cancel").Click Else Reporter.ReportEvent micPass , "Login Validation", "succesfully logged into flight reservation" Parameter("srslt") = "Pass" End If Else Reporter.ReportEvent micFail, "Login Validation", "Flight application is not opened" Parameter("srslt") = "Fail" End If Action2: - If Window("Flight Reservation").Exist Then Window("Flight Reservation").Close While Window("Flight Reservation").Exist(2) = True Wend If Window("Flight Reservation").Exist(3) = "False" Then Reporter.ReportEvent micPass, "Close Application", "Application is closed"
  • 62. Else Reporter.ReportEvent micFail,"close application","app is not closed" End If Else Reporter.ReportEvent micFail,"close app","app is not closed" End If New Order: - Open Order: -
  • 63. Fax Order: - 'Msgbox "Fax Order" Set objxl=CreateObject("Excel.Application") Set objwbk=objxl.Workbooks.Open ("D:Projectfaxorder.xls") Set objwst = objwbk.Worksheets("sheet1") Set objFile = CreateObject("Scripting.FileSystemObject") Set objptr = objFile.OpenTextFile("D:ProjectFlightDetails.txt",8) iRcnt=objwst.UsedRange.Rows.count Set obj= window("Flight Reservation") If obj.Exist (5) Then For indx = 2 to iRcnt obj.Activate obj.WinMenu("Menu").Select "File;Open Order..." obj.Dialog("Open Order").WinCheckBox("Order No.").Set "ON" obj.Dialog("Open Order").WinEdit("Edit_2").Set objwst.Cells(indx,1) obj.Dialog("Open Order").WinButton("OK").Click If obj.Dialog("Open Order").Dialog("Flight Reservations").Exist(5) Then obj.Dialog("Open Order").Dialog("Flight Reservations").WinButton("OK").Click obj.Dialog("Open Order").WinButton("Cancel").Click Reporter.ReportEvent micFail,"Open Order","Order number doesnt exist" objwst.Cells(indx,3) = "order number doesnt exist" objptr.WriteLine Parameter("sUname") & " tried to open order number " & objwst.cells(indx,1) & " which doesnt exist" Else obj.Activate
  • 64. obj.WinMenu("Menu").Select "File;Fax Order..." obj.Dialog("Fax Order No. *.*").WinObject("Fax Number:").Type objwst.cells(indx,2) 'obj.Window("Fax Order No. *.*").RunAnalog "Track2" @@ hightlight id_;_3016516_;_script infofile_;_ZIP::ssf1.xml_;_ obj.Dialog("Fax Order No. *.*").WinButton("Send").Click If obj.Dialog("Fax Order No. *.*").Dialog("Flight Reservations").Exist(5) Then obj.Dialog("Fax Order No. *.*").Dialog("Flight Reservations").WinButton("OK").Click Reporter.ReportEvent micFail,"Send Fax","Not able to send fax" objwst.Cells(indx,3) = "Not able to send fax" objptr.WriteLine Parameter("sUname") & " tried to send fax to " & objwst.cells(indx,2) & " but not able to send fax" obj.Dialog("Fax Order No. *.*").WinButton("Cancel").Click Else While obj.Dialog("Fax Order No. *.*").Exist(3)="True" Wend sFaxMsg = obj.WinObject("AfxWnd40").GetROProperty("Text") If sFaxMsg = "Fax Sent Successfully..." Then Reporter.ReportEvent micPass,"Send Fax" , "Fax Sent Successfully" objptr.WriteLine Parameter("sUname") & " has successfully sent fax to " & objwst.cells(indx,2) objwst.Cells(indx,3) = "Fax sent successfully" End If End If End If Next Else Reporter.ReportEvent micFail,"Select Fax Order","Flight Reservation Window doesnot exist" End If objwbk.Save objwbk.Close objxl.Quit Set objwst = nothing Set objwbk = nothing Set objxl = nothing Set obj = nothing Set objptr = nothing Set objfile = nothing Delete order: - 'Msgbox "Delete order" Set objxl = CreateObject ("Excel.Application") Set objwb = objxl.Workbooks.Open("D:Projectdeleteorder.xls") Set objst = objwb.Worksheets("sheet1") Set objFile = CreateObject("Scripting.FileSystemObject") Set objptr = objFile.OpenTextFile("D:ProjectFlightDetails.txt",8) Set obj = Window("Flight Reservation") iRcnt = objst.UsedRange.rows.count If obj.Exist(2)Then For indx = 2 to iRcnt sOnum = objst.cells(indx,1) If sOnum>10 Then
  • 65. RunAction "openord [openorder] [2]", oneIteration, sOnum, bOpen If bOpen Then Reporter.ReportEvent micPass,"Open Order","Opened the order to delete" If obj.WinButton("Delete Order").GetROProperty("Enabled")="True" Then obj.WinButton("Delete Order").Click If obj.Dialog("Flight Reservations").Exist Then obj.Dialog("Flight Reservations").WinButton("Yes").Click objst.cells(indx,2) = "Deleted order number "& sOnum objptr.WriteLine Parameter("sUname") & " has successfully deleted the order " & sOnum End If End If Else Reporter.ReportEvent micFail,"Delete Order","Order number doesnt exist" objst.cells(indx,2) =sOnum & " order number doesnt exist" objptr.WriteLine Parameter("sUname") & " tried to open order " & sOnum & " but order doesnt exist" End If Else Reporter.ReportEvent micFail,"Delete Order","Cannot delete orders below 10" objst.cells(indx,2) = "Cannot delete order number "& sOnum objptr.WriteLine Parameter("sUname") & " tried to delete order " & sOnum & " but cannot delete orders less than 10" End If Next End If objwb.Save objwb.Close objxl.Quit Set objst = nothing [ Set objwb = nothing Set objxl = nothing Set objptr = nothing Set objfile = nothing] Orders: - Set objxl = CreateObject ("Excel.Application") Set objwb = objxl.Workbooks.Open("D:Projectusers.xls") Set objst = objwb.Worksheets("sheet1") Set objFile = CreateObject("Scripting.FileSystemObject") Set objptr = objFile.CreateTextFile("D:ProjectFlightDetails.txt",8) ircnt = objst.UsedRange.Rows.Count For indx =2 to ircnt sUname = objst.cells(indx,1) sPwd = objst.cells(indx,2) RunAction "Login [ActionDemo] [2]", oneIteration, sUname, sPwd, Result Role = objst.cells(indx,3) Select Case Role Case "new order" RunAction "Action1 [neworder] [2]", oneIteration, iOrdno RunAction "Logout [ActionDemo] [2]", oneIteration objptr.WriteLine sUname & " has placed a new order generating order number: " & iOrdno objptr.Close Case "open order" RunAction "openord [openorder] [2]", oneIteration, iOrdno, bOpen RunAction "Logout [ActionDemo] [2]", oneIteration