Programming Concepts in QTP With some Basic Examples.

76
Programming Concepts in QTP With some Basic Examples

Transcript of Programming Concepts in QTP With some Basic Examples.

Page 1: Programming Concepts in QTP With some Basic Examples.

Programming Concepts in QTP

With some Basic Examples

Page 2: Programming Concepts in QTP With some Basic Examples.

Automation Object ModelAutomation Object Model

Automating QuickTest Operations

Just as you use QuickTest to automate the testing of your applications, you can use the QuickTest Professional automation object model to automate your QuickTest operations. Using the objects, methods, and properties exposed by the QuickTest automation object model, you can write programs that configure QuickTest options and run tests or components instead of performing these operations manually using the QuickTest interface.

Automation programs are especially useful for performing the same tasks multiple times or on multiple tests or components, or quickly configuring QuickTest according to your needs for a particular environment or application.

Page 3: Programming Concepts in QTP With some Basic Examples.

About Automating QuickTest Operations

You can use the QuickTest Professional automation object model to write programs that automate your QuickTest operations. The QuickTest automation object model provides objects, methods, and properties that enable you to control QuickTest from another application.

What is Automation?

Automation is a Microsoft technology that makes it possible to access software objects inside one application from other applications. These objects can be easily created and manipulated using a scripting or programming language such as VBScript or VC++. Automation enables you to control the functionality of an application programmatically.

An object model is a structural representation of software objects (classes) that comprise the implementation of a system or application. An object model defines a set of classes and interfaces, together with their properties, methods and events, and their relationships

Page 4: Programming Concepts in QTP With some Basic Examples.

What is the QuickTest Automation Object Model?

Essentially all configuration and run functionality provided via the QuickTest interface is in some way represented in the QuickTest automation object model via objects, methods, and properties. Although a one-on-one comparison cannot always be made, most dialog boxes in QuickTest have a corresponding automation object, most options in dialog boxes can be set and/or retrieved using the corresponding object property, and most menu commands and other operations have corresponding automation methods.

You can use the objects, methods, and properties exposed by the QuickTest automation object model, along with standard programming elements such as loops and conditional statements to design your program.

Automation programs are especially useful for performing the same tasks multiple times or on multiple tests or components, or quickly configuring QuickTest according to your needs for a particular environment or application.

For example, you can create and run an automation program from Microsoft Visual Basic that loads the required add-ins for a test or component, starts QuickTest in visible mode, opens the test or component, configures settings that correspond to those in the Options, Test or Business Component Settings, and Record and Run Settings dialog boxes, runs the test or component, and saves the test or component.

Page 5: Programming Concepts in QTP With some Basic Examples.

Regression Testing & Regression Testing & AutomationAutomation

When Automation is applicable?When Automation is applicable?

Regression Testing Cycles are long and iterative.Regression Testing Cycles are long and iterative.

If the application is planned to have multiple releases / buildsIf the application is planned to have multiple releases / builds

If it’s a long running application where in small enhancements / If it’s a long running application where in small enhancements / Bug Fixes keeps happeningBug Fixes keeps happening

Test Repeatability is required Test Repeatability is required

Page 6: Programming Concepts in QTP With some Basic Examples.

You can then add a simple loop to your program so that your single program can perform the operations described above for multiple tests or components.

You can also create an initialization program that opens QuickTest with specific configuration settings. You can then instruct all of your testers to open QuickTest using this automation program to ensure that all of your testers are always working with the same configuration.

Deciding When to Use QuickTest Automation Programs

Like the tests or components you design using QuickTest, creating a useful QuickTest automation program requires planning, design time, and testing. You must always weigh the initial investment with the time and human-resource savings you gain from automating potentially long or tedious tasks.

Any QuickTest operation that you must perform many times in a row or must perform on a regular basis is a good candidate for a QuickTest automation program.

The following are just a few examples of useful QuickTest automation programs:

Initialization programs — You can write a program that automatically starts QuickTest and configures the options and the settings required for recording on a specific environment.

Page 7: Programming Concepts in QTP With some Basic Examples.

Maintaining your tests or components — You can write a program that iterates over your collection of tests and components to accomplish a certain goal. For example:

· Updating values—opening each test or component with the proper add-ins, running it in update run mode against an updated application, and saving it in order to update the values in all of your tests and components to match the updated values in your application. · Applying new options to existing tests or components—When you upgrade to a new

version of QuickTest, you may find that the new version offers certain options that you want to apply to your existing tests and components. You can write a program that opens each existing test and component, sets values for the new options, then saves and closes it.

Calling QuickTest from other applications—You can design your own applications with options or controls that run QuickTest automation programs. For example, you could create a Web form or simple Windows interface from which a product manager could schedule QuickTest runs, even if the manager is not familiar with QuickTest.

Page 8: Programming Concepts in QTP With some Basic Examples.

To check through QTP if the process is To check through QTP if the process is running or notrunning or not

We can do this job with a simple VBScript code. This will reduce the duration of work flow to less than 2 seconds and you get the result instantly at the click of a button

Code:

Dim AllProcessDim ProcessDim strFoundProcessstrFoundProcess = FalseSet AllProcess = GetObject("winmgmts:") 'create objectFor Each Process In AllProcess.InstancesOf("Win32_process") 'Get all the processes running in your PC

If (Instr (Ucase(Process.Name),"TASKMGR.EXE") = 1) Then 'Made all uppercase to remove ambiguity. Replace TASKMGR.EXE with your application name in CAPS.

msgbox "Application is already running!" 'You can replace this with Reporter.ReportEvent

strFoundProcess = True

Page 9: Programming Concepts in QTP With some Basic Examples.

Exit forEnd IfNext

If strFoundProcess = False Thenmsgbox "Go ahead!Application is not running" 'You can replace this with Reporter.ReportEventEnd If

Set AllProcess = nothing

To check whether this is working:

1) Copy the above code to a notepad and save file as test.vbs on your desktop.

2) Open the Windows Task Manager[Ctrl-Shift-Esc].

3) Double click on file created above(test.vbs)

4) You should get a message "Application is already running!"

5) Done...Enjoy!

Page 10: Programming Concepts in QTP With some Basic Examples.

How to Run QTP from Outside when it is How to Run QTP from Outside when it is already closed and Openings QTP already closed and Openings QTP

Scripts at a Schedule TimeScripts at a Schedule Time

There can be situations when you need to schedule your QTP scripts so that they can run when you are not present in front of your PC. I will show you a demo below.

1) Create a .vbs file to launch QTP with required settings, add-ins etc. This code will open your QTP and run your script froma specified location when it is actually closed (Pretty cool ..)

Here is a sample vbs code

Page 11: Programming Concepts in QTP With some Basic Examples.

Set App = CreateObject("QuickTest.Application")App.LaunchApp.Visible = TrueApp.WindowState = "Maximized" 'Maximize QTP windowApp.ActivateView "ExpertView" 'Display Expert ViewApp.open "C:\Test1", False 'Opens test in editable modeApp.Test.Run 'Runs the testApp.Quit 'Close QTP

2) ok, for the newbies. Create a sample QTP test and save it as Test1 at the location above. Copy the code into notepad and name the file as testing.vbs

3) Now we will automate the opening of vbs file through Windows Scheduler. Go To Start > Control Panel > Schedule Tasks > Click Add Schedule Tasks Click Next on the screen.

Page 12: Programming Concepts in QTP With some Basic Examples.

4) Click Browse and and select the .vbs file you just created.You will get this screen

Page 13: Programming Concepts in QTP With some Basic Examples.

5) Give a name to the task and select the frequency for performing the given tasks. For this demo we will select "One time only"

Page 14: Programming Concepts in QTP With some Basic Examples.

6) Select Start Time and Start Date. For this demo, select Start Time as current time+5 mins and Start date as todays date.

7) Next Screen Enter "UserName", "Password" and "Confirm Password" Click Next and you should get this screen.

8) Click on Finish and yo Man, you're done.

Page 15: Programming Concepts in QTP With some Basic Examples.

Date Driven Testing Using ExcelSheet, Date Driven Testing Using ExcelSheet, Notepad and DatatableNotepad and Datatable

Data Driven Testing using notepad

Set f=CreateObject("Scripting.FileSystemObject")Set f1=f.CreateTextFile("c:\text.txt")f1.writeline "aaa bbb"f1.writeline "ccc ddd"

The above script creates a notepad in C: drive with following contents:aaa bbbccc ddd

Set f2=f.OpenTextFile("c:\text.txt")While f2.AtEndOfStream <>truef3=f2.readlinex=Split(f3, "")msgbox x(0)msgbox x(1)WEnd

Page 16: Programming Concepts in QTP With some Basic Examples.

The above script is used for data driven using notepad directly. Here we are not importing data to excel sheet. Directly values are retreived from notepad. We are using while loop and reading each line till the end. Split function splits the line where space(" ")occurs. Line is divided to 2 parts.one before space and other after space. For example we have 1st line in notepad as aaa bbb

here aaa is 1st part and bbb is 2nd part

x(0)=aaax(1)=bbb

all values are read this way using while loop. One point to note here is if any line is empty in notepad datadriven testing is stopped before that line. It will not proceed further.so we have to give values without any empty lines in notepad. To make things more clear,

Suppose u have

aaa bbbccc ddd

Datadriven is stopped at aaa and bbb only because next line is empty. Datadriven is stopped after 1st line.

Page 17: Programming Concepts in QTP With some Basic Examples.

Datadriven using dataTable

This Script gives result by retrieving values from datatable.A B5 56 67 78 89 9In datatable enter test data as shown above. Fill values below "A" and "B"script required for DDT(data driven testing)is

val1=datatable("A",1)val2=datatable("B",1)res=cint(val1) +cint(val2)msgbox res

Result will be 10,12,14,16,18.

datatable("column name",sheetname/id)cint is a function which converts string to integer.

check what will happen if u are not using cint in third step.just replace this res=val1+val2 in place of res=cint(val1) +cint(val2)

Page 18: Programming Concepts in QTP With some Basic Examples.

Challenges in Regression Testing – Why Challenges in Regression Testing – Why we go for Automationwe go for Automation

Eventually, in any software system, users may defects or we can say bugs in thedeveloped program. Normally, these bugs are fixed, the fixes are then tested, and the updatedsoftware is released back to the users . However, since the software is so tightly coupled or we can due to the interconnected nature of software, even the smallest change can wreakunpredictable havoc when the implications of that change are not properly understood.

Any software change, even one that corrects a known defect, can affecta system in an unforeseen manner and potentially cause problems that are worsethan those that the change was originally trying to address.

Regression testing is the practice of retesting of a software system that has beenmodified to ensure that no previously-working functions have failed as a result ofdefect reparations or newly added functionality.

Comprehensive regression testing fully ensures that a software system is functioning as designed. Comprehensive regression testing, however, is rarely feasible, given the time and resource constraints placed on the typical software development team.

Page 19: Programming Concepts in QTP With some Basic Examples.

As a software system expands and evolves, it becomes more and more difficult to test every piece of functionality. This problem is compounded by the frequency of software builds. In anenvironment where software builds are done on a nightly basis, comprehensiveregression testing of every build is essentially impossible. Typically, in theseenvironments, the testing of previous functionality is foregone to allow for testing ofnew fixes and new functionality. This leaves open the possibility that the softwareteam will release software with undiscovered defects.

Hence we go for an Automation tool that helps us in addressing these challenges. Through an Automation tool, we create scripts and which are quite helpful in retesting the original system's functionality. Every time we get a new build, we execute the created automation scripts to check the previous working functionality. And the most important benefit of automation is that we can execute scripts in an unattended mode means it frees QA persons to do other important tasks while the scripts are running automatically.

Page 20: Programming Concepts in QTP With some Basic Examples.

Descriptive Programming Descriptive Programming

Example to Count and Close all Open Bowsers

Script to get count,names of all open browsers and to close them.

Set b=Description.Createb("micclass").value="Browser"Set obj=Desktop.ChildObjects(b)msgbox obj.countFor i=0 to obj.count-1c=obj(i).getroproperty("name")msgbox(c)obj(i).CloseNext

Page 21: Programming Concepts in QTP With some Basic Examples.

Example for Google search page

SystemUtil.run "iexplore.exe","http://www.google.com"Browser("name:=Google.*").Page("title:=Google.*").WebEdit("name:=q").set"Testing"Browser("name:=Google.*").Page("title:=Google.*").WebButton("name:=Google Search").Click

Example to check all Check Boxes in a WebPage

Usage of Description Object is shown below

Creates a new, empty description object in which you can add collection of properties and values in order to specify the description object in place of a test object name in a step.

Set Button=Description.Create()

Button("type").Value="submit"Button("name").Value="Google Search"Button("html tag").Value="INPUT"

Browser("Google").Page("Google").WebButton(Button).Click

Page 22: Programming Concepts in QTP With some Basic Examples.

TO CHECK ALL THE CHECKBOXES ON A PAGE USING CHILDOBJECTS PROPERTY

Dim obj_check

Set obj_check=Description.Create

obj_Check("html tag").value="INPUT"obj_Check("type").value="checkbox"

Dim allcheckboxesSet allcheckboxes=Browser("Browser").Page("orkut - home").ChildObjects(obj_check)a= allcheckboxes.count()msgbox a

For i=0 to (a-1)allcheckboxes(i).Set "ON"Next

Page 23: Programming Concepts in QTP With some Basic Examples.

Features of QTP 9.2Features of QTP 9.2

New to Quick Test Pro 9.2?

Are you new to HP Quick Test Pro 9.2 (QTP)? Say yes and you are at the right place, at the right time. This article is for newbie’s who want to start their carrier with QTP or have just started with QTP. The article will give you a brief overview of various features of QTP, and since it is for newbie’s we won’t be going into too much details of every feature.

What is QTP 9.2?

* HP Quick Test Pro 9.2 is a functional automation and regression testing tool* QTP provides record and playback of events* Uses VBScript as the scripting Language* Provides keyword view and expert view to view test cases.* Latest versions of QTP is 9.5 (launched in mid Jan 2008)* Previous version of QTP: 6.5, 8.0, 8.1, 8.2, 9.0, 9.1* QTP was previously owned by Mercury Interactive®

Page 24: Programming Concepts in QTP With some Basic Examples.

Launching QTP

When you launch QTP for the first time, Add-in manager window is displayed

What is Add-in?

* QTP requires Add-in for recognizing object of a specific environment* By default QTP 9.2 comes with 3 Add-ins: Web, ActiveX and VB* Some of the Add-ins available for QTP 9.2 are

1. Terminal Emulator (TE)2. .NET3. Java4. SAP5. Siebel6. Stingray7. VisualAge8. Web Services

* QTP does not require any Add-in to work on Standard windows application* Add-ins can only be loaded when starting QTP

Page 25: Programming Concepts in QTP With some Basic Examples.

Once the selected Add-ins are loaded, QTP window will show up

Hit the record button to start recording. If you are recording for the first time, the Record and Run Settings dialog box opens.

What all tabs are shown in above dialog would depend on Add-ins that is loaded. Using above dialog we can set on what all application should QTP record on.

Note: If QTP does not record anything on your application then make sure you have the correct settings specified in Record and Run Settings…

Keyword view

The Keyword View enables you to create and view the steps of your test in a keyword-driven, modular, table format. This is the only view where complete Test flow can be viewed.

Expert View

In Expert View, QTP displays each operation performed on the application in the form of a script, comprised of VBScript statements. Complete test flow is not available/visible in this view.

Page 26: Programming Concepts in QTP With some Basic Examples.

Test and Run-time Object

* QTP works on objects in Application Under Test (AUT) by storing object description* This object description is known as a Test Object* Each Test Object supports predefined sets of Methods and properties* The actual object in the AUT which is identified for a Test Object is called the Run-time object.* A Test Object can always be present without the AUT* Run-time object can only be present when AUT is up and running

Object Spy

Object Spy is a tool that can be used to spy Test and run time object for looking at properties and methods supported by object being spied

Page 27: Programming Concepts in QTP With some Basic Examples.

Object Identification

* QTP uses three types of properties when identifying a object

1. Mandatory – Always learn these properties for the object2. Assistive – Learn in case Mandatory properties are not enough to identify the object uniquely3. Ordinal identifiers – Learn in case both mandatory and assistive properties are not able to recognize the objects correctly

* Ordinal identifiers are of three types:1. Index – index of object (0, 1, 2 …)2. Location – Location of the object on the screen (0, 1, 2 …)3. CreationTime – Used only for Browser. Launchtime of browser (0, 1, 2 …)

Page 28: Programming Concepts in QTP With some Basic Examples.

Object Identification Settings

Launch from menu Tools->Object Identification…

Here we can Add/Remove properties from/to Mandatory and Assistive properties. Objects in application represent certain special characteristics which allow QTP to map them QTP Test object. For window objects this characteristic is mostly define by ”regexpwndclass“. In case application developers don’t use standard class names while creating object QTP won’t be able to identify the object correctly. Below is a checkbox in Search window recognized by QTP as WinObject

By clicking on the ”User Defined…“ button on Object identification settings window, we can add such objects and map. Once added QTP will now be able to recognize the object correctly.

Object Hierarchy

* QTP uses object hierarchy to identify object inside a AUT* QTP only adds those objects from hierarchy which are necessary for it to identify the object later.* In this case QTP will addBrowser(”Google“).Page(”Google“).WebEdit(”q“).Set ”test“ (WebTable object ignored)* QTP cannot be configured to record such objects automatically.

Page 29: Programming Concepts in QTP With some Basic Examples.

Object Repository (OR)

* QTP works on object in application by storing information about the object in Object repository* All objects on which user takes an action while recording are automatically added to object repository* ”Browser“, ”Google“, ”q“ are three different objects that would be present in OR for the below generated statement

Browser("Browser").Page("Google").WebEdit("q").set ”Test“

* Copying and pasting code from one script to another script does not work in QTP as the OR does not get copied to the new script* There are two types of Object Repositories in QTP:1. Shared OR: Can be used by multiple scripts. A central location to store all objects2. Per-Action OR: Every action has its individual object repository

Per-Action Object Repository

* Default repository* Specific to actions (Will be used only for a particular action)* Preferable when application is not dynamic with respect to time* Cannot be reused

Page 30: Programming Concepts in QTP With some Basic Examples.

Shared Action repository

* Can be updated by all actions accessing it* Preferable when application is dynamic with respect to time* Used in most automation projects* Needs maintenance and administration

Action

* Provides way of grouping code into business logic* Are pretty similar to Functions in VBScript* Have their own Data Table and Object Repository (in case of per-action object repository)* Supports input and output parameters* Actions are of two types: normal and re-usable* Re-usable actions can be called in other Test.* QTP does not allow calling another test within a test* TestFlow represent the top level action. Complete test flow can only be viewed in Keyword views

Page 31: Programming Concepts in QTP With some Basic Examples.

Inserting Actions

* There are three ways to insert a Action in a test1. Insert Call to New…2. Insert Call to Copy…3. Insert Call to Existing…

* Insert Call to New… - Creates a new action and adds a call to the same. Pfrovide the name "Cancel Ticket" in the "Name" field and click on OK button.* Adds below line to the code

RunAction "Cancel Ticket", oneIteration

Actions - Insert Call to Existing…

* Insert Call to Existing – User to insert call to a re-usable action located within the same test or some other test* This inserts the call to the existing action. In case the action in present in some other test case then a read only copy of action is inserted

Page 32: Programming Concepts in QTP With some Basic Examples.

Actions – Insert Call to Copy…

* Insert Call to Copy - Inserts call to an existing re-usable action and creates an editable copy of that action* Actions cannot be deleted from a Test from Expert view. To delete a action one must go to the keyword view and delete the action* An action call cannot be inserted directly by writing code in Expert View, it has to be added through the GUI first.

Action Iterations

An action can be run for 1 or more rows from its Local Data Table.

* QTP supports there types of iteration modes:1. Run one iteration only2. Run on all rows3. Run from Row to Row

* Similar to Action, a test can also be run for multiple iterations from Global Data Table

Page 33: Programming Concepts in QTP With some Basic Examples.

Why Parameterization?

* Parameterization allows us to pick different values at run time.* Reduces Time and Effort.* Usage of data drivers allows us to use the same data for various input boxes.* Parameterization can also be done for checkpoints.

Data Table

* Data Table is excel like spreadsheet which can be user for parameterizing a test case* DataTable are of two types:1. Global Data Table – Data table for Test flow2. Local data table – Data table for every action

* Data table value can be accessed using the below methoda) DataTable("",dtGlobalSheet)b) DataTable("",dtLocalSheet)c)DataTable("","")

Page 34: Programming Concepts in QTP With some Basic Examples.

Run-time Data table

* Any changes made to Data table during run-time is stored in run-time data table.* Run-time data table is available in the test results summary of a test* DataTable values can be changed at run-time by using below mentioned code:

DataTable(”OrderConf“, dtGlobalSheet) = ”ABCD1234“

Resources

* Scripts written in VBScript language can be add as a Resource to the test* All code written in the script is available across all Actions* A VBScript can also be loaded in an Action by using ExecuteFile function. Ex –ExecuteFile ”C:\Init.vbs“* In case of multiple files QTP combines all the files into a single one and executes the code. The files are combine in bottom to top order

Page 35: Programming Concepts in QTP With some Basic Examples.

Environment Variables

* Environment variables are global variables available to all Actions* They can be used to run a test case on different environment* To add a new Environment variable go to Test -> Settings…->Environment (Tab)* Environment variables are of two types

1. Built-in2. User-Defined

* Built in environment variables give information about the system and the current test* User-defined Environment variables added in the Environment tab of Test Settings are Read-only during the test run* Environment variables can be added during runtime also using codeEnvironment.Value(”OrderNumber“) = ”ABCDEF“* Environment variables can be loaded at run-time from a XML file using the below codeEnvironment.LoadFromFile "C:\TestEnvironment.xml"* The Environment XML file has to be in below format:

APP_URLhttp://test1.appserver.com

Page 36: Programming Concepts in QTP With some Basic Examples.

Parameters

* Parameters provide another way of parameterizing the test cases* There are two types of parameters:1. Test parameters2. Action parameters

* Test parameters can be set in Test->Settings…->Parameters (Tab)* Test parameters value can be provided when replaying the test* Test arguments can be accessed in the test using TestArgs(”“)

Action Parameters

* Used to pass parameters to Action* Output parameters can only be used when Action is being called for a single iteration* Ex – RunAction "Login", oneIteration, "TestUser", "TestPass", out* A parameter can be accessed usingParameter("ParamName")

Page 37: Programming Concepts in QTP With some Basic Examples.

Checkpoints

* Checkpoints are verification points in a test* Test without checkpoint would never have a pass status* Checkpoints can be of types– Built-in checkpoints– Custom checkpoints* Types of Built-in checkpoints available are

1. Standard checkpoints: Verify properties of an object2. Text checkpoints: Verify text presence between two strings3. Text Area checkpoint4. Bitmap checkpoint5. Accessibility checkpoint6. Database checkpoint7. XML Checkpoint

* Only Database and XML checkpoints can be inserted in idle mode.* Rest all checkpoints can only be added during Recording or through Active screens.* Checkpoint code

Browser("Google").Page("Google").WebEdit("q").Check CheckPoint("Verify TextBox_Standard")

Page 38: Programming Concepts in QTP With some Basic Examples.

Custom Checkpoints

* Custom checkpoints can be created using Code

loginExist = Browser().Page().Link(”text:=Login“).Exist(0)If loginExist thenReporter.ReportEvent micPass, ”Check Login“, ”Login link exists“ElseReporter.ReportEvent micFail, ”Check Login“, ”Login link does not exists“End if

* Custom checkpoint can be made flexible based on implementation and are preferred over Built-in checkpoints

Test Results

Test results provide a execution summary of the complete test case* There are different types of status in test results summary:1. Passed2. Failed3. Done4. Warning5. Information

Page 39: Programming Concepts in QTP With some Basic Examples.

Descriptive Programming

* Alternate way of writing test cases without having objects in object repository* Descriptive programming can be done in two ways

1. Using object description2. Using string description

* In DP objects are identified by describing all the identification properties* String description DPBrowser(”title:=Google“).Page(”title:=Google“).WebButton(”name:=Search“).Click* Object Based DPSet btnSearch = Description.Create : btnSearch(”name“).Value = ”Search“Set brwGoogle = Description.Create : brwGoogle(”title“).value = ”Google“Set pgGoogle = Description.Create : pgGoogle(”title“).value = ”Google“Browser(brwGoogle).Page(pgGoogle).WebButton(btnSearch).Click

Page 40: Programming Concepts in QTP With some Basic Examples.

Description objects can also be used to get all child objects matching a criterion. Ex –

Set oDesc = Description.CreateoDesc(”name”).Value = ”txt_.*“oDesc(”name”).RegularExpression = TrueSet allMatchingObjects = Browser().Page().ChildObjects(oDesc)Msgbox allMatchingObjects.CountMsgbox allMatchingObjects(0).GetROProperty(”name“)

* By default all property values are considered as regular expression patterns* When using string description all regular expression must be used with escape character for literal meaning. Ex - …Link(”text:=Logout \(Piyush\)“).Click

* DP based Object repository can be created in any file* Code can be copied from one script to another without copying the object repository* Custom implementation of object is easier. Ex –

objStrDesc = ”Browser(”“title:=Test““).Page(”“title:=Test““).Link(”“text:=Login““)“Execute ”Set obj = ” & objStrDescobj.Click

Page 41: Programming Concepts in QTP With some Basic Examples.

QTP Misc information

* QTP and the AUT has to be on the same machine* QTP can be controlled remotely from another machine* QTP scripts cannot be run without QTP

Page 42: Programming Concepts in QTP With some Basic Examples.

QTP and Excel – Part 1 QTP and Excel – Part 1

How can we use the data table to provide input data to an application?

Use the DataTable.Value method to access data from the data table and input it into the application

For data in the Global datasheet

Page 43: Programming Concepts in QTP With some Basic Examples.

1. Open a new script.2. In column A of the Global datasheet, enter the data in three rows.3. Go to www.google.com.4. Begin recording.5. Type a value into the Google search field.6. Stop recording.7. Go to the Expert view. Modify the script so it look like this:

rc = DataTable.Value ("A", dtGlobalSheet)msgbox rcBrowser("Google").Page("Google").WebEdit("q").Set rc

8. To run all rows in the global data table, go to Test ->; Test Settings -> Run tab, and select "Run on all rows."

For data in the Local datasheet:

Page 44: Programming Concepts in QTP With some Basic Examples.

1. Start a new script.2. In column A of the Action1 datasheet, enter the data in three rows:3. Go to www.google.com.4. Begin recording.5. Type a value into the Google search field.6. Stop recording.7. Go to the Expert view. Modify the script so it look like this:

rc = DataTable.Value ("A",dtLocalSheet)msgbox rcBrowser("Google").Page("Google").WebEdit("q").Set rc

8. To run all rows:

Right-click on the Action name in the Tree View.

Go to Action Properites -> Run tab, and select "Run all rows."

Page 45: Programming Concepts in QTP With some Basic Examples.

Similarly, How can we use the data table to get output data from an application?

Create an Output Value. The text will be placed in the datatable and can be accessed as needed.

1. Once you see the text you want to retrieve, start recording.2. From the Insert menu, select Output Value, then Text Output Value.3. Click on the desired text. The "Text Output Value Properties" window will appear.4. In the window you can verify or set the Before and After text settings.5. By default the retrieved value will be added to the Global sheet. You can modify the settings by selecting Output Text in the combo box, then clicking Modify.6. Once satisfied, click OK.

Page 46: Programming Concepts in QTP With some Basic Examples.

An Output statement will be entered into the script.

Example:Browser("Browser").Page("Page").Output CheckPoint("Text")msgbox DataTable.Value("PageOutput_Text_out", dtGlobalSheet)

In addition, a column (in the example, PageOutput_Text_out) will be inserted into the datatable(Remember in the runtime datatable), with the output text.

OR Another method to retrieve data during run time is to do just the opposite of what we did above in the first question above.

DataTable.Value(ParameterID [, SheetID])=NewValue

Page 47: Programming Concepts in QTP With some Basic Examples.

Note:

The value property is the default property for the DataTable object. As the default property you do not need to explicitly use .Value.

DataTable(ParameterID [, SheetID]) = NewValue

Example:' Add data to the current row of the Global sheetDataTable("VarName", dtGlobalSheet) = "new value" ' Using DataTable by itselfDataTable.Value("VarName2", dtGlobalSheet) = "new value2" ' Using .Value

' Add data to the current row of the Local sheetDataTable("VarName", dtLocalSheet) = "new value" ' Using DataTable by itselfDataTable.Value("VarName2", dtLocalSheet) = "new value2" ' Using .Value

Page 48: Programming Concepts in QTP With some Basic Examples.

QTP and Excel – Part 2QTP and Excel – Part 2

Introduction of External Data Sheet

In QTP, we have an option for Data Table which comes very useful when the user wants to parameterize his/her test. The parameters set by user appear by default in the Columns of the sheet. Not only is this helpful for parameterized operation of your test also when you want to work with the Output function of QTP you can use this table since the corresponding outputs can be viewed over here.

This option can be as per the user requirement and in this the user can make an Excel sheet with the required parameters in it. Also one can import and export the contents to his test while running it.

Import External Data File

The user shall perform the following operations:

In this once the user has created the Excel sheet and has recorded the test, (s)he shall right click on any of the cells in the Data Table and select the File>Import, user will get a window where (s)he will have to select the exact location of the excel sheet.

Page 49: Programming Concepts in QTP With some Basic Examples.

On Clicking the option, user will get a window pop-up box asking whether you will want to replace the contents of the current data table with the ones in the excel sheet. Click OK and proceed.

Select the exact location of the excel file on your PC which you want to import.

The contents of the excel sheet shall appear in the Data Table of QTP once you selected the required excel sheet.

Remember to use the same naming convention through-out the script, you have used in the file. Each of the column name in your excel file will become one parameter.

Secondly the actions for which the user shall be setting parameters need to be given the same name as in the imported excel file. As shown below, while recording the file the user has selected a particular value for the Action which he wants to parameterize which will appear in the constant option.

Page 50: Programming Concepts in QTP With some Basic Examples.

The user has to choose the Parameter option and then type the exact name as in the Data table for e.g.: “No_Pass”, here we are parameterizing the no of passengers for whom the tickets have to be booked and will re-run the script for that much time.

Page 51: Programming Concepts in QTP With some Basic Examples.
Page 52: Programming Concepts in QTP With some Basic Examples.

Points to note regarding which location to select OR whether to make a sheet global or local.

1. Globally implies the user has the Global sheet of the data table filled up with certain data. Now when he runs the test it will operate for the amount of rows that are filled in this sheet.

2. If you want a condition that for single row run of the global sheet there should be run of another sheet namely the “Action 1” of the data table we call the operation as Local.

3. In this it is important that the user selects the Parameter option as local and not global as in the above condition and the required contents will come in Action 1 sheet.

4. Now initially if while you are importing if there were two sheets created by you then by default the contents of the second sheet will be Action 1. It is only that the corresponding Action be parameterized properly.

Page 53: Programming Concepts in QTP With some Basic Examples.

Now, In the keyword view, Right click on the Action 1 and select Action Call Properties and then in the Run Tab select the no of rows for which you want to run the Local sheet.

When the user runs this script, for every single row of the Global sheet, the Action 1 sheet will run for all of its respective columns.

A similar method can be used to import a single sheet or a database file.

Also from within the script you can use Datatable.Import("path of file")

Page 54: Programming Concepts in QTP With some Basic Examples.

Export External Data File

Like importing data sheet we can also export the entire data table into an external excel file. This is basically useful if one wants to use the required parameters in some different test run within QTP.

Similar to the exporting of complete file we can also export an single sheet from the data table

Also from within the script you can use Datatable.Export("path of file")

Page 55: Programming Concepts in QTP With some Basic Examples.

QTP Interview questions QTP Interview questions

Quick Test Professional: Interview Questions and answers.

1. What are the features and benefits of Quick Test Pro(QTP)?

1. Key word driven testing2. Suitable for both client server and web based application3. VB script as the script language4. Better error handling mechanism5. Excellent data driven testing features

2. How to handle the exceptions using recovery scenario manager in QTP?

You can instruct QTP to recover unexpected events or errors that occurred in your testing environment during test run. Recovery scenario manager provides a wizard that guides you through the defining recovery scenario. Recovery scenario has three steps1. Triggered Events2. Recovery steps3. Post Recovery Test-Run

Page 56: Programming Concepts in QTP With some Basic Examples.

3. What is the use of Text output value in QTP?

Output values enable to view the values that the application talks during run time. When parameterized, the values change for each iteration. Thus by creating output values, we can capture the values that the application takes for each run and output them to the data table.

4. How to use the Object spy in QTP 8.0 version?

There are two ways to Spy the objects in QTP1) Thru file toolbar: In the File ToolBar click on the last toolbar button (an icon showing a person with hat).2) Thru Object repository Dialog: In Object repository dialog click on the button “object spy…” In the Object spy Dialog click on the button showing hand symbol. The pointer now changes in to a hand symbol and we have to point out the object to spy the state of the object. If at all the object is not visible or window is minimized then hold the Ctrl button and activate the required window to and release the Ctrl button.

5. What is the file extension of the code file and object repository file in QTP? File extension ofPer test object rep: filename.mtrShared Object rep: filename.tsrCode file extension id: script.mts

Page 57: Programming Concepts in QTP With some Basic Examples.

6. Explain the concept of object repository and how QTP recognizes objects?

Object Repository: displays a tree of all objects in the current component or in the current action or entire test( depending on the object repository mode you selected).we can view or modify the test object description of any test object in the repository or to add new objects to the repository.Quicktest learns the default property values and determines in which test object class it fits. If it is not enough it adds assistive properties, one by one to the description until it has compiled the unique description. If no assistive properties are available, then it adds a special Ordinal identifier such as objects location on the page or in the source code.

7. What are the properties you would use for identifying a browser and page when using descriptive programming?

“name” would be another property apart from “title” that we can use. ORWe can also use the property “micClass”.ex: Browser(”micClass:=browser”).page(”micClass:=page”)

8. What are the different scripting languages you could use when working with QTP?

You can write scripts using following languages:Visual Basic (VB), XML, JavaScript, Java, HTML

Page 58: Programming Concepts in QTP With some Basic Examples.

9. Tell some commonly used Excel VBA functions.

Common functions are:Coloring the cell, Auto fit cell, setting navigation from link in one cell to other saving

10. Explain the keyword createobject with an example.

Creates and returns a reference to an Automation objectsyntax: CreateObject(servername.typename [, location])Argumentsservername:Required. The name of the application providing the object.typename : Required. The type or class of the object to create.location : Optional. The name of the network server where the object is to be created.

11. Explain in brief about the QTP Automation Object Model.

Essentially all configuration and run functionality provided via the QuickTest interface is in some way represented in the QuickTest automation object model via objects, methods, and properties. Although a one-on-one comparison cannot always be made, most dialog boxes in QuickTest have a corresponding automation object, most options in dialog boxes can be set and/or retrieved using the corresponding object property, and most menu commands and other operations have corresponding automation methods. You can use the objects, methods, and properties exposed by the QuickTest automation object model, along with standard programming elements such as loops and conditional statements to design your program.

Page 59: Programming Concepts in QTP With some Basic Examples.

12. How to handle dynamic objects in QTP?

QTP has a unique feature called Smart Object Identification/recognition. QTP generally identifies an object by matching its test object and run time object properties. QTP may fail to recognize the dynamic objects whose properties change during run time. Hence it has an option of enabling Smart Identification, wherein it can identify the objects even if their properties changes during run time.Check out this: If QuickTest is unable to find any object that matches the recorded object description, or if it finds more than one object that fits the description, then QuickTest ignores the recorded description, and uses the Smart Identification mechanism to try to identify the object.While the Smart Identification mechanism is more complex, it is more flexible, and thus, if configured logically, a Smart Identification definition can probably help QuickTest identify an object, if it is present, even when the recorded description fails.

The Smart Identification mechanism uses two types of properties: Base filter properties - The most fundamental properties of a particular test object class; those whose values cannot be changed without changing the essence of the original object. For example, if a Web link’s tag was changed from to any other value, you could no longer call it the same object. Optional filter properties - Other properties that can help identify objects of a particular class as they are unlikely to change on a regular basis, but which can be ignored if they are no longer applicable.

Page 60: Programming Concepts in QTP With some Basic Examples.

13. What is a Run-Time Data Table? Where can I find and view this table?

In QTP, there is data table used, which is used at runtime.-In QTP, select the option View->Data table.-This is basically an excel file, which is stored in the folder of the test created, its name is Default.xls by default.

14. How does Parameterization and Data-Driving relate to each other in QTP?

To data driven we have to parameterize. i.e. we have to make the constant value as parameter, so that in each interaction(cycle) it takes a value that is supplied in run-time data table. Through parameterization only we can drive a transaction (action) with different sets of data. You know running the script with the same set of data several times is not suggested, and it’s also of no use.

15. What is the difference between Call to Action and Copy Action.?

Call to Action: The changes made in Call to Action, will be reflected in the original action (from where the script is called). But where as in Copy Action , the changes made in the script ,will not effect the original script(Action)

Page 61: Programming Concepts in QTP With some Basic Examples.

16. Explain the concept of how QTP identifies object.

During recording qtp looks at the object and stores it as test object. For each test object QT learns a set of default properties called mandatory properties, and look at the rest of the objects to check whether this properties are enough to uniquely identify the object. During test run, QTP searches for the run time objects that matches with the test object it learned while recording.

17. Differentiate the two Object Repository Types of QTP.

Object repository is used to store all the objects in the application being tested.Types of object repository: Per action and shared repository.In shared repository only one centralized repository for all the tests. where as in per action for each test a separate per action repository is created.

18. What the differences are and best practical application of Object Repository?

Per Action: For Each Action, one Object Repository is created.Shared: One Object Repository is used by entire application

Page 62: Programming Concepts in QTP With some Basic Examples.

19. Explain what the difference between Shared Repository and Per Action Repository

Shared Repository: Entire application uses one Object Repository , that similar to Global GUI Map file in WinRunnerPer Action: For each Action, one Object Repository is created, like GUI map file per test in WinRunner

20. Have you ever written a compiled module? If yes tell me about some of the functions that you wrote.

Sample answer (You can tell about modules you worked on. If your answer is Yes then You should expect more questions and should be able to explain those modules in later questions): I Used the functions for Capturing the dynamic data during runtime. Function used for Capturing Desktop, browser and pages.

21. Can you do more than just capture and playback?

Sample answer (Say Yes only if you worked on): I have done Dynamically capturing the objects during runtime in which no recording, no playback and no use of repository is done AT ALL.-It was done by the windows scripting using the DOM(Document Object Model) of the windows.

Page 63: Programming Concepts in QTP With some Basic Examples.

22. How to do the scripting. Are there any inbuilt functions in QTP? What is the difference between them? How to handle script issues?

Yes, there’s an in-built functionality called “Step Generator” in Insert->Step->Step Generator -F7, which will generate the scripts as you enter the appropriate steps.

23. What is the difference between check point and output value?

An output value is a value captured during the test run and entered in the run-time but to a specified location.EX:-Location in Data Table[Global sheet / local sheet]

24. How many types of Actions are there in QTP?

There are three kinds of actions:Non-reusable action - An action that can be called only in the test with which it is stored, and can be called only once.Reusable action - An action that can be called multiple times by the test with which it is stored (the local test) as well as by other tests.External action - A reusable action stored with another test. External actions are read-only in the calling test, but you can choose to use a local, editable copy of the Data Table information for the external action.

Page 64: Programming Concepts in QTP With some Basic Examples.

25. I want to open a Notepad window without recording a test and I do not want to use System utility Run command as well. How do I do this?

You can still make the notepad open without using the record or System utility script, just by mentioning the path of the notepad “( i.e. where the notepad.exe is stored in the system) in the “Windows Applications Tab” of the “Record and Run Settings window.

Page 65: Programming Concepts in QTP With some Basic Examples.

Tips for Working on QTPTips for Working on QTP

1# How to open the Application Browser?

We can do this with the following code

Set objIE = CreateObject("InternetExplorer.Application")objIE.visible = TrueobjIE.Navigate environment("URL_ENV")

Here the URL specified in the Enviroment file will be navigated. But if we want to directly place the URL in the above mentioned code, replace the third line with the below mentioned line:

objIE.Navigate "www.google.com"

Page 66: Programming Concepts in QTP With some Basic Examples.

2# How to check if a parameter exists inside the DataTable or not?

Use the following code:

On Error Resume Nextval=DataTable("ParamName",dtGlobalSheet)if Err.number<> 0 then'Parameter does not existelse'Parameter existsend if

If no error is there, then Err.number = 0

3# How to know if my checkpoint passes or not?chk_PassFail = Browser(...).Page(...).WebEdit(...).Check (Checkpoint("Check1"))if chk_PassFail thenMsgBox "Check Point passed"else MsgBox "Check Point failed"end if

"if chk_PassFail" means if chk_PassFail="True". In the above mentioned code, a boolean value is returned to the variable chk_PassFail.

Page 67: Programming Concepts in QTP With some Basic Examples.

4# How can I generate a random number?

The below mentioned code generates a randomnumber in the range of 100-999 :RandomNumber (100,999)

5# My test fails due to checkpoint failing, how can I see the result of my checkpoint without affecting my test case to checkpoint failure?

Reporter.Filter = rfDisableAll 'Disables all the reporting events like Pass or even Failchk_PassFail = Browser(...).Page(...).WebEdit(...).Check (Checkpoint("Check1"))Reporter.Filter = rfEnableAll 'Enable all the reporting events like Pass or even Failif chk_PassFail thenMsgBox "Check Point passed"elseMsgBox "Check Point failed"end if

6# What is the difference between an Action and a function?Action is a thing specific to QTP while functions are a generic thing which is a feature of VB Scripting. Action can have a object repository associated with it while a function can't. A function is just lines of code with some/none parameters and a single return value while an action can have more than one output parameters.

Page 68: Programming Concepts in QTP With some Basic Examples.

7# Where to use function or action?Well answer depends on the scenario. If you want to use the OR feature then you have to go for Action only. If the functionality is not about any automation script i.e. a function like getting a string between to specific characters, now this is something not specific to QTP and can be done on pure VB Script, so this should be done in a function and not an action. Code specific to QTP can also be put into an function using DP. Decision of using function/action depends on what any one would be comfortable using in a given situation.

8# When to use a Recovery Scenario and when to us On Error Resume Next?Recovery scenarios are used when you cannot predict at what step the error can occur or when you know that error won't occur in your QTP script but could occur in the world outside QTP, again the example would be "out of paper", as this error is caused by printer device driver. "On error resume next" should be used when you know if an error is expected and dont want to raise it, you may want to have different actions depending upon the error that occurred. Use err.number & err.description to get more details about the error.

Page 69: Programming Concepts in QTP With some Basic Examples.

9# How to use environment variable?A simple definition could be... it is a variable which can be used across the reusable actions and is not limited to one reusable action. We can use Environment variables like a global variables.There are two types of environment variables:

1. User-defined2. Built-inWe can retrieve the value of any environment variable. But we can set the value of only user-defined environment variables.

To set the value of a user-defined environment variable:Environment (VariableName) = NewValue

To retrieve the value of a loaded environment variable:CurrValue = Environment (VariableName)

ExampleThe following example creates a new internal user-defined variable named MyVariable with a value of 10, and then retrieves the variable value and stores it in the MyValue variable.

Environment.Value("MyVariable")=10MyValue=Environment.Value("MyVariable")

Page 70: Programming Concepts in QTP With some Basic Examples.

10# How Should I rename my checkpoint inside QTP 9.0?Example:Browser("Google").Page("Google").WebEdit("Search").Check CheckPoint("Search")In the above example, the user would like to change the name of the CheckPoint object from "Search" to something which is of our convinienceNote:

This functionality is new to QuickTest Professional 9.0.This is not available for QTP 8.2 and below.

1. Right-click on the Checkpoint step in the Keyword View or on the Checkpoint object in Expert View.2. Select "Checkpoint Properties" from the pop-up menu.3. In the Name field, enter the new checkpoint name.4. Click . The name of the checkpoint object will be updated within the script.Example:Browser("Google").Page("Google").WebEdit("Search").Check CheckPoint("Search")

Page 71: Programming Concepts in QTP With some Basic Examples.

Note:You must use the QuickTest Professional user interface to change the name of the checkpoint. If you manually change the name of the checkpoint in the script, QuickTest Professional will generate an error during replay. The error message will be similar to the following:

"The "" CheckPoint object was not found in the Object Repository. Check the Object Repository to confirm that the object exists or to find the correct name for the object."

The CheckPoint object is not a visible object within the object repository, so if you manually modify the name, you may need to recreate the checkpoint to resolve the error.

Page 72: Programming Concepts in QTP With some Basic Examples.

11# Does QuickTest Professional support Internet Explorer 7.0?QuickTest Professional 9.1QuickTest Professional 9.1 supports Microsoft Internet Explorer 7.0 Beta 3. Internet Explorer version 7.0 is now certified to work and to be tested with QuickTest Professional version 9.1.QuickTest Professional 9.0QuickTest Professional 9.0 supports Internet Explorer 7.0 Beta 2.QuickTest Professional 8.2 and belowQuickTest Professional 8.2 and below do not include support for Internet Explorer 7.0.

Does QuickTest Professional support Firefox?QuickTest Professional 9.1 and 9.2QuickTest Professional 9.1 provides replay support for Mozilla Firefox 1.5 and Mozilla Firefox 2.0 Alpha 3 (Alpha-level support for Bon Echo 2.0a3).Notes:

QuickTest Professional 9.1 will not record on FireFox. You can record a test on Microsoft Internet Explorer and run it on any other supported browser, such as FireFox.

The .Object property for web objects is not supported in FireFox.

Page 73: Programming Concepts in QTP With some Basic Examples.

QuickTest Professional 9.0QuickTest Professional 9.0 provides replay support for Mozilla FireFox 1.5.Notes:

QuickTest Professional 9.0 will not record on FireFox. You can record a test on Microsoft Internet Explorer and run it on any other supported browser, such as FireFox.

The .Object property for web objects is not supported in FireFox.

QuickTest Professional 8.2 and below

QuickTest Professional 8.2 and below do not have support for Firefox.

Page 74: Programming Concepts in QTP With some Basic Examples.

12# How to check if a dropdown item contains some values?

Here we have a dropdown list named Items which contains 3 items :Item1, Item2 and Item3. We want to check if Item3 is there in the dropdown or not.

str_ItemType=Browser("..").Page("..").WebList("lst_itemType").GetROProperty("all items") str_ItemType1=Instr(str_ItemType,"Item4")

If str_ItemType1=0 Then

Reporter.ReportEvent 0,"Item Type","Verify that Items dropdown list does not contains Item4"

Else

Reporter.ReportEvent 1,"Item Type","Verify that Items dropdown list does not contains Item4"

Page 75: Programming Concepts in QTP With some Basic Examples.

13# What is the lservrc file in QTP?

The lservrc file contains the license codes that have been installed

The lservrc file contains the license codes that have been installed. Whenever a new license is created, the license code is automatically added to this file. The lservrc file is a text file, with no extension.

File Location:

1) For a Concurrent (Floating) license installation:

"#server installation directory#\#language#"

Example:C:\Program Files\XYZ Technologies\ABC Server\English\lservrc

2) For a Seat (Stand-alone) license installation:

#AQT/QTP installation directory#\bin"

Example:C:\Program Files\Mercury Interactive\QuickTest Professional\Bin\lservrc

Page 76: Programming Concepts in QTP With some Basic Examples.

14# What to do if you are not able to run QTP from quality center?This is for especially for newbies with QTP.Check that you have selected Allow other mercury products to run tests and components from Tools--> Options--> Run Tab.

15# Does QuickTest Professional support Macintosh operating systems?No, QTP is not expected to run on this OS.