Uploaded by harish.sangu

QTP Interview Questions

advertisement
End
QuickTest Pro Interview Questions
01. How to encrypt a password in QuickTest Professional? ..................................... 2
02. How to get number of pages in PDF file? ........................................................ 2
03. How to display quotation marks (") in QTP? .................................................... 2
04. How to minimize/maximize QTP window? ....................................................... 3
05. How to set/get system time and date? ........................................................... 3
06. How to get font size/color and other attributes of Link Object? .......................... 4
07. What are the different methods and properties of IE’s DOM object? ................... 4
08. How to get text of Status Bar from QTP? ........................................................ 5
09. How to capture tool tips of images? ............................................................... 5
10. How to capture tool tip of link? ..................................................................... 5
11. How get current browser URL? ...................................................................... 5
12. Different ways to get & count objects in QTP? ................................................. 6
13. How to get all Object Indentification Properties? ............................................. 7
14. How to create and open a excel application? ................................................... 8
15. What are the different ways to synchronize a test? .......................................... 9
16. How to use ordinal identifiers to identify an object? ....................................... 10
17. What are the different ways to launch application? ........................................ 11
18. How to create a dynamic array? .................................................................. 12
19. What are Environment Variables? ................................................................ 13
20. How to get text from a dialog? .................................................................... 14
21. How to compare two images? ..................................................................... 15
22. How to execute the code in a notepad? ........................................................ 16
23. How to use connect to a database? ............................................................. 17
24. In how many ways we can declare a variable? .............................................. 18
25. What is the difference between action and function? ...................................... 19
26. How to count and close all open browsers? ................................................... 20
27. How to open a context menu?..................................................................... 21
End of the document ...................................................................................... 21
Home
Home
01. How to encrypt a password in QuickTest Professional?
str = "Some Text"
encrStr = Crypt.Encrypt(str)
02. How to get number of pages in PDF file?
' Function GetNumPagesInPDF returns the number of pages in PDF file
' FileName - path to given ODF file
' If a file isn't found, then -1 will be returned
Function GetNumPagesInPDF(FileName)
Dim oPDFDoc
Set oPDFDoc = CreateObject( "AcroExch.PDDoc" )
If oPDFDoc.Open( FileName ) Then
GetNumPagesInPDF = oPDFDoc.GetNumPages()
Set oPDFDoc = Nothing
Else
GetNumPagesInPDF = -1
End If
End Function
' Call GetNumPagesInPDF function with a full path of PDF file
numPages = GetNumPagesInPDF("FilePath")
MsgBox "Number of pages: " & numPages
03. How to display quotation marks (") in QTP?
' Double the quotes ("")
MsgBox "#1: ""QTP - QuickTest Professional"""
' Use ANSI character code - Chr(34)
MsgBox "#2: " & Chr(34) & "QTP - QuickTest Professional" & Chr(34)
Home
Home
04. How to minimize/maximize QTP window?
' Using Minimize/maximize method of Window object
' If a window is located in Object Repository
WN = Browser("browser_name").GetROProperty("hwnd")
Window("hwnd:=" & WN).Minimize
Window("hwnd:=" & WN).Maximize
' Using QTP Application object - QuickTest.Application
' QuickTest Automation Object Model Approach
Sub MinimizeQTPWindow ()
Set qtApp = CreateObject("QuickTest.Application")
Set qtApp = GetObject("","QuickTest.Application")
qtApp.WindowState = "Minimized"
Set qtApp = Nothing
End Sub
Call MinimizeQTPWindow()
05. How to set/get system time and date?



Now - Function returns the current date and time according to the setting
of your computer's system date and time.
Date - Function returns the current system date.
Time - Function returns a Variant of subtype Date indicating the current
system time.
We can set the time and date using Run method of WScript.Shell object.
NowVal = Now
' Displays #3/23/2010 12:31:19 PM#
DateVal = Date
' Displays #3/23/2010#
TimeVal = Time
' Displays #12:31:19 PM#
DateVal = #3/29/2010#
TimeVal = #1:31:19 PM#
Set OShell = CreateObject("Wscript.Shell")
OShell.Run "cmd /K date " & CStr(DateVal) & " & Exit"
OShell.Run "cmd /K time " & CStr(TimeVal) & " & Exit"
' Open a DOS command window, change the path to C:\ and run the DIR
OShell.Run "cmd /K CD C:\ & Dir"
Home
Home
06. How to get font size/color and other attributes of Link Object?
' Using Link Identification Properties
' background color, color, font properties
ColorValue = Browser("Gmail").Page("Gmail").Link(Gmail)._
GetROProperty("color")
FontValue = Browser("Gmail").Page("Gmail").Link(Gmail)._
GetROProperty("font")
BackColorValue = Browser("Gmail").Page("Gmail").Link(Gmail)._
GetROProperty("background color")
' Using currentStyle object
' backgroundColor, color, fontSize, fontStyle, fontFamily, fontWeight
Set ctrlWebEl = Browser("Gmail").Page("Gmail").WebElement("Gmail")
Set objWebEl = ctrlWebEl.Object
sColor = objWebEl.currentStyle.color
sBackgrColor = objWebEl.currentStyle.backgroundColor
sFontSize = objWebEl.currentStyle.fontSize
sFontStyle = objWebEl.currentStyle.fontStyle
sFontFamily = objWebEl.currentStyle.fontFamily
sFontWeight = objWebEl.currentStyle.fontWeight
07. What are the different methods and properties of IE’s DOM object?
Browser("bname").Object is a reference to the Internet Explorer's DOM object. To be
more precise, it's a reference to the Internet Explorer's IWebBrowser2 interface.
Using Browser("bname").Object, you can access different methods and properties of
IE, for example:
# Statement
Meaning
1 Browser("bname").Object.GoBack
Navigates backward one item in the history
list
2 Browser("bname").Object.LocationURL Gets the URL of the page that is currently
displayed
3 Browser("bname").Object.StatusText
Sets or gets the text in the status bar for
the object
4 Browser("bname").Object.ToolBar
Sets or gets whether toolbars for the object
are visible
Home
Home
08. How to get text of Status Bar from QTP?
' Getting text of Status Bar using Object.StatusText property of IE object
sText = Browser("QTP").Object.StatusText
MsgBox sText
' Getting text of Status Bar using GetROProperty("text") method of WinStatusBar
' object for a browser object
sText = Browser("QTP").WinStatusBar("msctls_statusbar32")._
GetROProperty("text")
MsgBox sText
' Getting text of Status Bar using GetContent method of WinStatusBar
' object for a windows object
sText = Window("Outlook").WinStatusBar("msctls_statusbar32")._
GetContent
MsgBox sText
09. How to capture tool tips of images?
' Using Image Identification Properties
' alt property
Browser("Gmail").Page("Gmail").Image(Gmail).FireEvent "onmouseover"
TooltipValue = Browser("Gmail").Page("Gmail").Image(Gmail)._
GetROProperty("alt")
10. How to capture tool tip of link?
' Place mouse cursor over the link
Browser("Yahoo!").Page("Yahoo!").WebElement("text:=My Yahoo!")._
FireEvent "onmouseover"
Tooltip= Window("nativeclass:=tooltips_class32").GetROProperty("text")
11. How get current browser URL?
' Page Identification Properties
' url property
UrlValue = Browser("Gmail").Page("Gmail").GetROProperty("url")
' Using URL property of Internet Explorer's DOM Object
UrlValue = Browser("Gmail").Page("Gmail").Object.URL
Home
Home
12. Different ways to get & count objects in QTP?
Method 1: QTP Descriptive Programming and ChildObjects QTP function.
Set oDesc = Description.Create()
oDesc("micclass").Value = "Link"
Set Links = Browser("Labs").Page("Labs").ChildObjects(oDesc)
Msgbox "Total links: " & Links.Count
Method 2: DOM Object collections, methods and properties
Set TestObject = Browser("Google").Page("Google")
' Using Links collection object
Set Links = TestObject.Object.Links
' Using all collection object
Set Links = TestObject.Object.all.tags("a")
' Using GetElementsByTagName method
Set Links = TestObject.Object.GetElementsByTagName("a")
For i = 0 to (Links.Length-1)
Print Links(i).innerText
Next
Method 3: XPath queries in QTP
' to get an HTML source code of Web page
HtmlCode = Browser("Google Labs").Page("Google Labs").Object._
documentElement.outerHtml
' save HTML code to a local file
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.CreateTextFile("C:\HtmlCode.html", True, -1)
f.Write(HtmlCode)
f.Close()
' run tidy.exe to convert HTML to XHTML
Set oShell = CreateObject("Wscript.shell")
oShell.Run "C:\tidy.exe --doctype omit -asxhtml -m -n C:\HtmlCode.html",
1, True ' waits for tidy.exe to be finished
' create MSXML parser
Set objXML = CreateObject("MSXML2.DOMDocument.3.0")
objXML.Async = False
objXML.Load("C:\HtmlCode.html")
XPath = "//a" ' XPath query means to find all links
Set Links = objXML.SelectNodes(XPath)
Msgbox "Total links: " & Links.Length
Home
Home
13. How to get all Object Indentification Properties?
' QTP can read Object Indentification Properties from Windows Registry
Const HKEY_LOCAL_MACHINE = &H80000002
Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\._
\root\default:StdRegProv")
sKeyPath = "SOFTWARE\Mercury Interactive\QuickTest Professional_
\MicTest\Test Objects\Link\Properties"
oReg.EnumValues HKEY_LOCAL_MACHINE, sKeyPath, arrNames
' arrNames array contains all names of properties
sNames = "Identfication Properties:" & vbNewLine
For i = 0 to UBound(arrNames)
sNames = sNames & arrNames(i) & vbNewLine
Next
MsgBox sNames
' Properties of Test Object
Set TOTestLink = Browser("Google").Page("Google").Link("Search")
' Properties of Run-time Object
Set RTTestLink = Browser("Google").Page("Google").Link("text:=Search")
sNamesTO = "GetTOProperty for Test Object" & vbNewLine &_
"Identfication Properties: Values" & vbNewLine
sNamesRO = "GetROProperty for Test Object" & vbNewLine &_
"Identfication Properties: Values" & vbNewLine
For i = 0 to UBound(arrNames)
sNamesTO = sNamesTO & arrNames(i) & ": " &_
TOTestLink.GetTOProperty(arrNames(i)) & vbNewLine
sNamesRO = sNamesRO & arrNames(i) & ": " &_
TOTestLink.GetROProperty(arrNames(i)) & vbNewLine
Next
MsgBox sNamesTO ' Test Object Properties of Test Object
MsgBox sNamesRO ' Run-time Object Properties of Test Object
Home
Home
14. How to create and open a excel application?
' Creating a new excel application
Set ExcelApp = CreateObject("Excel.Application")
ExcelApp.Application.Visible = True
ExcelApp.Workbooks.Add
Set ExcelBook = ExcelApp.ActiveWorkbook
Set ExcelSheet = ExcelApp.ActiveSheet
ExcelApp.ActiveSheet.Name = "Test"
ExcelSheet.Cells(2, "C").Value = "Hi"
Val = ExcelSheet.Cells(2, "C").Value
MsgBox Val
ExcelBook.SaveAs FilePath
ExcelApp.Application.Quit
' Opening a existing excel application
Set ExcelApp = CreateObject("Excel.Application")
ExcelApp.Application.Visible = True
Set ExcelBook = ExcelApp.Workbooks.Open(FilePath)
Set ExcelSheet = ExcelBook.Worksheets("Sheet1")
Val1 = ExcelSheet.Cells(2, "B").Value
Val2 = ExcelSheet.Cells(2, "C").Value
MsgBox Val1
MsgBox Val2
ExcelApp.Application.Quit
Home
Home
15. What are the different ways to synchronize a test?
Method 1: Creating Synchronization Points
Browser("Mercury").Page("Mercury").WebElement("New"). WaitProperty_
"visible", True, 10000
Method 2: Adding Exist and Wait Statements
Syncs = Browser("Gmail").Page("Gmail").Frame("fr").Link("New").Exist
Cnt = 1
While Not Syncs
Syncs = Browser("Gmail").Page("Gmail").Frame("fr").Link("New").Exist
Cnt = Cnt + 1
If (Cnt = 10) Then
Syncs = True
End if
Wend
Method 3: Sync Method: (For only Browser and Page Objects)
Waits for the browser to complete the current navigation.
' The following example uses the Sync method to wait for the browser object
SystemUtil.Run "C:\Program Files\Internet Explorer\IEXPLORE.EXE"
Browser("Index:=0").Sync
Browser("Index:=0").Navigate ("http://www.rediff.com")
' The following example uses the Sync method to wait for the page object
Browser("title:=.*").Page("title:=.*").Sync
Method 4: Modifying Timeout Values

When working with tests, to modify the maximum amount of time that
QuickTest waits for an object to appear, change the Object Synchronization
Timeout in the File > Settings > Run tab.

To modify the amount of time that QuickTest waits for a Web page to load,
change the Browser Navigation Timeout in the File > Settings > Web
tab.
Home
Home
16. How to use ordinal identifiers to identify an object?
QuickTest can use the following types of ordinal identifiers to identify an object:
Index:
Indicates the order in which the object appears in the application code relative to
other objects with an otherwise identical description. Index property values are
object-specific.
While learning an object, QuickTest can assign a value to the test object's Index
property to uniquely identify the object. The value is based on the order in which the
object appears within the source code. The first occurrence is 0.
Location:
Indicates the order in which the object appears within the parent window, frame,
or dialog box relative to other objects with an otherwise identical description.
While learning an object, QuickTest can assign a value to the test object's Location
property to uniquely identify the object. The value is based on the order in which the
object appears within the window, frame, or dialog box, in relation to other objects
with identical properties. The first occurrence of the object is 0. Values are assigned
in columns from top to bottom, and left to right. Location property values are objectspecific.
CreationTime: (Browser object only)
Indicates the order in which the browser was opened relative to other open
browsers with an otherwise identical description.
While learning a browser object, if QuickTest is unable to uniquely identify the object
according to its test object description, it assigns a value to the CreationTime test
object property. This value indicates the order in which the browser was opened
relative to other open browsers with an otherwise identical description. The first
browser that opens receives the value CreationTime = 0.
Home
Home
17. What are the different ways to launch application?
Method 1: SystemUtil Object
Syntax: SystemUtil.Run file, [params], [dir], [op], [mode]
Usage: In most situations SystemUtil.Run statement is used to run applications or to
open files in their default application.
Example: SystemUtil.Run "D:\My Music\"
Method 2: InvokeApplication
Syntax: InvokeApplication(Command [,StartIn])
Usage: The InvokeApplication method can open only executable files and is used
primarily for backward compatibility.
Example: InvokeApplication "C:\Program Files\Internet Explorer\IEXPLORE.EXE"
Method 3: WshShell Object
Syntax: object.Run(strCommand, [intWindowStyle], [bWaitOnReturn])
Usage: The Run method starts a program running in a new Windows process. You
can have your script wait for the program to finish execution before continuing. This
allows you to run scripts and programs synchronously.
Example:
Set WshShell = CreateObject ("Wscript.shell")
WshShell.Run Chr(34) & "C:\Program Files\Internet Explorer\IEXPLORE.EXE" &
Chr(34)
Set WshShell = Nothing
Method 4: Using Run dialog of Windows
1. Add the Windows Start button to the Object Repository using the "Add
Objects" button in Object Repository dialog.
2. Open the Run dialog (Start > Run), and learn the "Open" edit field and the
"OK" button into the Object Repository.
3. Switch to the Expert View, and manually add the lines to open the Run dialog.
4. Manually enter the lines to enter the information to launch the application,
and click the "OK" button of the Run dialog.
Example:
Dialog("Run").WinEdit("Open:").Type "notepad"
Dialog("Run").WinButton("OK").Click
Home
Home
18. How to create a dynamic array?
The ReDim statement is used to size or resize a dynamic array that has already
been formally declared using a Private, Public, or Dim statement with empty
parentheses (without dimension subscripts). You can use the ReDim statement
repeatedly to change the number of elements and dimensions in an array.
Syntax: ReDim [Preserve] varname(subscripts) [, varname(subscripts)] . . .
If you use the Preserve keyword, you can resize only the last array dimension, and
you can't change the number of dimensions at all. For example, if your array has
only one dimension, you can resize that dimension because it is the last and only
dimension. However, if your array has two or more dimensions, you can change the
size of only the last dimension and still preserve the contents of the array.
The following example shows how you can increase the size of the last dimension of
a dynamic array without erasing any existing data contained in the array.
ReDim X(10, 10, 10)
...
ReDim Preserve X(10, 10, 15)
Caution: If you make an array smaller than it was originally, data in the eliminated
elements is lost.
When variables are initialized, a numeric variable is initialized to 0 and a string
variable is initialized to a zero-length string (""). A variable that refers to an object
must be assigned an existing object using the Set statement before it can be used.
Until it is assigned an object, the declared object variable has the special value
Nothing.
Home
Home
19. What are Environment Variables?
The Environment tab includes the following options for the Variable type:
Built-in. Variables that represent information about the test and the computer on
which the test is run, such as Test path and Operating system. These variables are
accessible from all tests, and are designated as read-only.
User-Defined Internal. Variables that you define within the test. These variables
are saved with the test and are accessible only within the test in which they were
defined. You can create or modify internal, user-defined environment variables for
your test in the Environment tab of the Test Settings dialog box or in the Parameter
Options dialog box.
User-Defined External. Variables that you predefine in the active external
environment variables file. You can create as many files as you want and select an
appropriate file for each test, or change files for each test run. Note that external
environment variable values are designated as read-only within the test.
Environment Object:
Enables you to work with environment variables. You can set or retrieve the value of
environment variables using the Environment object. You can retrieve the value of
any environment variable. You can set the value of only user-defined, environment
variables.
Associated Methods and Properties
 ExternalFileName Property
 LoadFromFile Method
 Value Property
' Retrieving value for built in environmental variable
OSVersionValue = Environment.Value("OSVersion")
' Defining User Defined internal environmental variable
Environment.Value("Tester") = "Harish"
TesterName = Environment.Value("Tester")
' Defining User Defined external environmental variable
<Environment>
<Variable>
<Name>Tester</Name>
<Value>Harish</Value>
</Variable>
</Environment>
Home
Home
20. How to get text from a dialog?
Method 1: Using Static object’s identification property
' Retrieve data from a dialog of a dialog
Pwd =Dialog("text:=Login").Dialog("text:=Flight Reservations")._
Static("text:=The password is '.*'" ).GetROProperty("text")
' Retrieve data from a dialog of a window
Vno = Window("regexpwntitle:=Flight Reservation").Dialog("text:=About_
Flight Reservation").Static("text:=Version.*").GetROProperty("text")
' Retrieve data from a dialog of a browser
Sxt = Brower("title:=Mercury").Dialog("text:=About Mercury")._
Static("nativeclass:=Static, Index:=0").GetROProperty("text")
Method 2: Using GetVisibleText method of Dialog object
' To retrieve message from a dialog of a browser
Err = Browser("title:= .*")._
Dialog("regexpwndtitle:= Microsoft Internet Explorer").GetVisibleText
' Retrieve data from a dialog of a dialog
Msg =Dialog("text:=Login")._
Dialog("text:=Flight Reservations").GetVisibleText
MsgBox Msg
Home
Home
21. How to compare two images?
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Set ObjFSO = CreateObject("Scripting.FileSystemObject")
Set ObjTS = ObjFSO.OpenTextFile(FilePath, ForWriting, True)
ObjTS.Write ("This is a test.")
ObjTS.Close
Set ObjTS = ObjFSO.OpenTextFile(FilePath, ForAppending, False)
ObjTS.Write ("<This is a test.>")
ObjTS.Close
Set ObjTS = ObjFSO.OpenTextFile(FilePath, ForReading, False)
Text = ObjTS.ReadAll()
MsgBox Text
ObjTS.Close
' Get the image files into strings
Const ForReading = 1 ' System will take ForReading as 1
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts1 = fso.GetFile(Img1).OpenAsTextStream(ForReading, -2)
Set ts2 = fso.GetFile(Img2).OpenAsTextStream(ForReading, -2)
' The value of TristateUseDefault constant is -2
Img1str = ts1.ReadAll
Img2str = ts2.ReadAll
ts1.Close
ts2.Close
StrCmpFlag = StrComp(Img1str, Img2str, vbBinaryCompare)
MsgBox StrCmpFlag
Home
Home
22. How to execute the code in a notepad?
Method 1: Using Eval statement
' Using Eval statement
SystemUtil.Run "C:\NotepadCmd.txt"
Window("Notepad").Activate
Window("Notepad").WinEditor("Edit").Type_
"Window(" & Chr(34) & "Notepad" & Chr(34) & ").Close"
Window("Notepad").WinMenu("Menu").Select "File;Save Ctrl+S"
Window("Notepad").WinEditor("Edit").Type micCtrlDwn + "s" + micCtrlUp
Expression = Window("Notepad").WinEditor("Edit").GetVisibleText
Eval Expression
Method 2: Associating text function libraries with test
The QuickTest Script Editor works with .qfl, .vbs, and .txt function library files.
In the Resources pane, right-click the Associated Function Libraries folder of the test
with which you want to associate a function library, and select Associate Existing
Function Library. The Open Function Library dialog box opens. Browse to and select
the function library you want to associate. Click Open. The function library is
associated with the test, and is displayed as a function library link in the Associated
Function Libraries folder in the tree.
To remove the function library from the test, right-click the function library and
select Remove Function Library, or select the function library and press the Delete
key.
Tip: If you want to associate the active function library, right-click and select
Associate Active Function Library.
Home
Home
23. How to use connect to a database?
1: Connection to the MS Access Database
' Connection to a MS Access database
Set ConObj = CreateObject("ADODB.Connection")
Set RecObj = CreateObject("ADODB.RecordSet")
DataSrc = "C:\Program Files\Mercury Interactive\QuickTest Professional_
\samples\flight\app\flight32.mdb"
ConnString ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="_
& DataSrc & ";User Id=admin;Password=;"
' ConnString = "flight32" ' If DSN ' flight32' is created
ConObj.Open ConnString
Sqlquery = "Select Count(*) as ItmsCnt from Orders"
' Set RecObj = ConObj.Execute(Sqlquery)
RecObj.Open Sqlquery, ConObj
ItmsCnt = RecObj.Fields("ItmsCnt").Value
2: Connection to the SQL Server Database
' Connection to a MS Access database
Set ConObj = CreateObject("ADODB.Connection")
Set RecObj = CreateObject("ADODB.RecordSet")
ConnString = "Driver={SQL Server};Server=localhost;_
Database=Northwind;Uid=sa;Pwd=sa;"
' ConnString = "Provider=sqloledb;Data Source=localhost;_
Initial Catalog=Northwind;User Id=sa;Password=sa;"
ConnObj.Open ConnString
Sqlquery = "Select Count(*) as ItmsCnt from Employee"
Set RecSetObj = ConnObj.Execute(Sqlquery)
ItmsCnt = RecSetObj.Fields("ItmsCnt").Value
Home
Home
24. In how many ways we can declare a variable?
Declaring Variables
In VBScript, variables are always of one fundamental data type, Variant.
VBScript has only one data type called a Variant. A Variant is a special kind of data
type that can contain different kinds of information, depending on how it is used.
Because Variant is the only data type in VBScript, it is also the data type returned by
all functions in VBScript.
You declare variables explicitly in your script using the Dim statement, the Public
statement, and the Private statement.
You can also declare a variable implicitly by simply using its name in your script.
That is not generally a good practice because you could misspell the variable name in
one or more places, causing unexpected results when your script is run. For that
reason, the Option Explicit statement is available to require explicit declaration of all
variables. The Option Explicit statement should be the first statement in your script.
Scope and Lifetime of Variables
A variable's scope is determined by where you declare it. When you declare a
variable within a procedure, only code within that procedure can access or change
the value of that variable. It has local scope and is a procedure-level variable. If you
declare a variable outside a procedure, you make it recognizable to all the
procedures in your script. This is a script-level variable, and it has script-level scope.
The lifetime of a variable depends on how long it exists. The lifetime of a script-level
variable extends from the time it is declared until the time the script is finished
running. At procedure level, a variable exists only as long as you are in the
procedure. When the procedure exits, the variable is destroyed. Local variables are
ideal as temporary storage space when a procedure is executing. You can have local
variables of the same name in several different procedures because each is
recognized only by the procedure in which it is declared.
Home
Home
25. What is the difference between action and function?
Action
VBScript Function
Actions contain Local Object Repository,
Data Table, a subfolder containing
snapshots, an Excel spreadsheet, and
other.
Functions do not have all these features.
Actions are internal to QTP.
Functions are both internal and external
to QTP.
Actions can have more than one input or
output parameter.
Functions can have more than one input
arguments, but they can have only one
return value.
Actions can or can not be reusable.
Functions are always reusable.
Action parameters can have default
values.
Functions do not have any default values.
Actions pass parameters by value only.
Functions can pass arguments by
reference and by value.
‘New’ statement cannot be used in
actions.
‘New’ statement can be used in functions.
Actions can only accept or return
Functions can accept arrays, dictionary
primative data types as parameters i.e., objects and test objects (i.e. Pages,
String, Boolean, Date, Number, Password. Frames, WebRadioGroups, etc.)
We cannot call actions recursively.
We can call functions recursively.
Home
Home
26. How to count and close all open browsers?
Method 1: Using Desktop childobjects
Dim Obj, ObjBsr
Set ObjBsr = Description.Create()
ObjBsr("micclass").Value = "Browser"
Set Obj = Desktop.ChildObjects(ObjBsr)
Cnt = Obj.Count()
Method 2: Using CreationTime Ordinal Identifier
Dim i : i = 0
While Browser("CreationTime:=[0-9]*").Exist
If Browser("CreationTime:=" & i).Exist Then
Browser("CreationTime:=" & i).Close
End If
i=i+1
Wend
Method 3: Using SystemUtil Object Methods
SystemUtil.CloseProcessByWndTitle "Microsoft Internet Explorer.*", True
closedCount = SystemUtil.CloseProcessByName("iexplore.exe")
HWND = Browser("title:=.*").GetROProperty("HWND")
SystemUtil.CloseProcessByHWND HWND
PID = Browser("title:=.*").GetROProperty("process id")
SystemUtil.CloseProcessByID PID
Method 4: Using Windows Management Instrumentation Object
strSQL = "Select * From Win32_Process Where Name = 'iexplore.exe'"
Set oWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set ProcColl = oWMIService.ExecQuery(strSQL)
For Each oElem in ProcColl
oElem.Terminate
Next
Set oWMIService = Nothing
Home
Home
27. How to open a context menu?
Method 1: Using Device Replay Object.
Const VK_R = 19
Const RIGHT_MOUSE_BUTTON = 2
Set NwkObj = CreateObject("WScript.Network")
Smt1 = "C:\Documents and Settings\" & NwkObj.UserName
Smt2 = "\Application Data\Microsoft\Internet ExplorerQuick Launch\"
SystemUtil.Run Smt1 & Smt2 & "Show Desktop.scf"
Set ctlr = DotNetFactory.CreateInstance("System.Windows.Forms.Control")
Do
Flag = MsgBox("Have positioned mouse?", vbYesNo)
Offset_x = ctlr.MousePosition.X
Offset_y = ctlr.MousePosition.Y
If Flag = 6 Then
Exit Do
End If
Loop
Set DevRpyObj = CreateObject("Mercury.DeviceReplay")
DevRpyObj.MouseClick Offset_x, Offset_y, RIGHT_MOUSE_BUTTON = 2
DevRpyObj.PressKey VK_R
Method 2: Using WScript Shell Object.
SystemUtil.Run "iexplore", "http://www.google.co.in/"
Set TestObject = Browser("Google").Page("Google").WebEdit("q")
Set WshShell = CreateObject("WScript.Shell")
hwnd = Browser("Google").GetROProperty("hwnd")
Window("hwnd:=" & hwnd).Activate
TestObject.Click ,,micRightBtn
WshShell.SendKeys "p"
Home
End of the document
Download