Learn UFT Step By Step Manner in a Fast Pace

UFT
Spread the love

Learn UFT or UFT Step By Step
Learn UFT or UFT Step By Step
Learn UFT or UFT Step By Step

Contents

Learn UFT Step By Step:

The topics we must cover while learning UFT are as follows:

  • Why do we need to use UFT?
  • Features of UFT
  • Assets of UFT with extensions.
  • How to work with UFT?
  • How to plan a Test?
  • How to understand UAT?
  • Configure and types of Licenses.
  • Install and Configure Add-Ins
  • How to create your test in UFT?
  • Recording modes of UFT.
  • Object Repository concept
  • Functions and Sub procedures in UFT
  • How to use the comment in UFT?
  • Object identification process
  • Step Generator
  • Datatypes in UFT
  • Variables in UFT
  • Looping and conditions in UFT
  • How to enhance Test?
  • Things to know of VBScript
  • Function Library concept in UFT
  • Synchronization concept in UFT
  • Actions in UFT
  • How to Parameterize your test?
  • How to work with Utility object?
  • How to work with checkpoint?
  • How to work with output values?
  • How to work with reporter Object?
  • How to write a custom HTML file?
  • Test Batch Runner
  • What is automation framework?
  • Introduction to Dictionary Object
  • Introduction to File System Object.
  • Difference between Action and Function
  • How to debug UFT script in VBscript debugger?
  • Errors and error handling of VBScript
  • The regular expression in UFT
  • Transactions in UFT
  • How to capture ajax events in UFT?
  • How to use Optional step in UFT?

Why UFT not Selenium?

UFT is a closed source software from HP. Many engineering brains are working the product better. Hence we need a license to use it. However, selenium is open source and there are not much engineers active supporting this. That does not mean it is bad.

While there lot of official help on same topics available directly from HP, Selenium lacks on that space. Testers need to try and find out the best solution.

UFT uses old VBscript hence ramping up from manual testing to UFT is easy but selenium needs knowledge on java, Perl or .NET to write effective code.

The easy recording is available for UFT whereas Selenium does not have an easy recording. We need to code from scratch.

UFT supports almost all known technologies whereas selenium supports web technology.

Lastly, UFT is very much user-friendly, selenium lacks in this space.

First Step to UFT

The first thing you need to learn is VBScript…the basics..The best place to learn VB script is —MSDN

Technology Supported by UFT:

 

Licenses of UFT:

UFT provides three types of licenses:

  1. Trial with limited facilities
  2. Seat License- tagged to the machine
  3. Concurrent License- depends on the number of users

What is a VBScript to an Automation Test Engineer?

VBScript (Visual Basic Script)

1. It is a scripting language scaled-down version of Visual Basic
2. It runs on client-side.
3. Basically a syntax-based language. Most VB syntaxes run on this.
4. For our purpose, we always save the file as “XYZ.vbs”

How to Work with UFT?

How to work with QTP is a systematic process. Lets us go through one by one…

Analyzing the application

In this phase, we check what kind of application on which tests need to be performed. If required we need to add the add-ins or we need to buy the add-ins.

Selecting Areas/Test Cases for Automation

After the successful pass of step-a, we will identify the manual test cases or the scenarios that we can automate. We can not automate 100% of the application in general.

Planning (Effort estimation, Schedule, Work allocation and Automation Framework implementation)

We will do an effort estimation for Step-b. We will also consider the schedule, framework effort in this phase.QTP records raw lines of codes. So transferring those from code to framework or add to existing framework is an effort. In the last phase, we will identify the team members and allocate them the work.

Creating Generic and project-specific functions

While recording we might get some generic function like button press..it is common to all the window/pages…this can a be a good trick to write a small function on button press and can reuse them. Or we might get a new flow which is very specific to a business.

Creating required Automation resources (Functions, Object repository Files, Environment variable files—etc)

This is as per the organization test strategy. If test strategy says we need to do record playback then it is ok to record and store objects in object repository or else we will go descriptive programming.

UFT Function and Sub Procedure

UFT allows all to run the same and repetitive tasks in the form of functions which can return some value and sub procedure which does not return any value.

Object Repository in UFT:

Object Repository in UFT or QTP
Object Repository in UFT or QTP

The post will cover the following topics Details of Object Repository in UFT,Details of Object Repository in QTP,add object repository in QTP,add object repository in uft,what is object repository in qtp explain,what is object repository in UFT explain,object repository in qtp with examples,object repository in UFT with examples,Object Repository in UFT,Object Repository in QTP. Apart from these you will also able to learn how to work export object repository to Excel and Automatic Object model to handle Object Repository.

Object Repository:

It is a storage place of UFT or QTP where we can store the objects information those are required for testing and it also acts as the interface between the test script and the AUT in order to identify the objects during execution.

So Object repository is a collection of objects and their properties. As it acts as an interface, with these properties QTP/UFT will be able to be to identify the objects and work on them. Similarly, if UFT/QTP cannot identify the objects, it will not be able to work on these objects.

In a simple term, an object is a graphic user element in an application and object repository is a graphical representation of the objects.

Object:

The object is something, which has structure and properties. Mostly this concept is based on OOPs hierarchy of Objects..It consists of data that describes the object [properties] and Functions that can be performed on that object[methods].

In OOPs an object is an instance of a class and in QTP or UFT, the objects are defined by the class. Like a go button in web, context is an instance of a web button.

Software objects:

We call windows, WebPages, buttons, edit boxes, check boxes, etc.. as software objects.

Types of Object in QTP:

There are four types of object available in QTP.

  1. Run time objects
  2. Test objects
  3. Utility objects
  4. Automation objects/User defined objects.
Run time objects:

During execution, the actual objects are called Runtime objects. The runtime objects are not present in the object repository. The objects present in the AUT. Ex: Buttons, links, etc…This is another important thing to learn on object repository in UFT with examples.

Test Objects:

Test objects are the replica of the actual objects(or controls) fetched from the application under test. It can be said test objects are references of Run time objects. They are UFT/QTP’s representation of the objects. This is another important thing to learn on object repository in UFT with examples.

Ex: WinEdit, WinButton, WebButton, Link, etc.
Note:
Test objects names vary from one environment to another.
Ex:

Run time objectsTest objects in Windows EnvironmentTest objects in VB
Environment
Test objects in web Environment
buttonsWinButtonVBButtonWebButton
Edit boxWinEditVBEditWebEdit
CheckboxWincheckboxVbcheckboxWebcheckbox

 

Utility objects

They are QTP/UFT reserved objects used for testing and result reporting. This is another important thing to learn on object repository in UFT with examples.

Ex:

  1. SystemUtil for launching/closing the application.
  2. The reporter for defining results.
  3. Services for inserting transaction points
  4. Environment for using environment variables
Automation objects/User defined objects

User can create objects; those can be used for performing specific operations. Ex: Creating objects in file system object class, adodb.connection class, dictionary object class, excel. Application class etc. This is another important thing to learn on object repository in UFT with examples.

More on User-defined Object:

If UFT/QTP refuses to recognize an object from the application(maybe standard classes does not support the object), UFT/QTP, in that case, will recognize the object as WinObject.

It is different than the common convention that you need to open UFT/QTP first then the application, otherwise, UFT/QTP will not be able to recognize the general objects and they will be identified as WinObjects.

The second reason why you may go to user-defined objects is that we want UFT/QTP to work an object just like another object. Like if we want to use combo box as button or link or any other control.

Navigation to create user-defined objects in UFT/QTP
  1. Click on Tool.
  2. Click on Object Identification.
  3. Object Identification window activates.
  4. Select Environment as a standard window.
  5. Click on User defined.
  6. Let the object mapping window open.
  7. Click on the class name or use hand symbol to identify the object.
  8. Click on the Map to drop down to select any other control.
  9. Click on add to create one more or click on OK to close the Object Mapping

This is how you create user-defined objects in UFT/QTP.

In general, there are two types of repository available in QTP/UFT
  1. Local repository (.MTR extension-Module Test Repository )
  2. Shared repository(.TSR extension- Test Shared Repository)
Local Repository:

For each action based test, the UFT will create and manage the individual repository. It is good when the test is small. It is local to test action. It is automatically saved in a test whenever we record a test. It resides in the bdb folder in action subfolder.File extension is .mtr(modular test repository). As this is local to any action, it can not be used for any other action or test. By default, QTP/UFT saves its objects to the local repository. This is another important thing to learn on object repository in UFT with examples.

How to locate the Local Object Repository?

  1. Open any test
  2. Navigate to Resource
  3. Click on Object Repository(Shortcut Ctrl+R)
Locate local Object repository
Locate local Object repository
  • QTP/UFT creates a Local Repository for every action automatically during Recording. That cannot be shared among tests.
  • User can add some more objects to Local repository
  • User can perform rename, delete operations in the local repository. As it is QTP/UFT’s internal file, the user no need to save modifications. In other words, it is auto-saved.
  • User can have multiple shared object repositories along with local object repository.
  • You can export the local object repository to the shared object repository.

In case if your test has shared object repository and local object repository attached to it, If you add a child object to local object repository and the parent of that object stays in the shared object repository, UFT/QTP will automatically move the parent to the local object repository.

Export OR to XML
Export OR to XML

If you add the same object from your application to two different actions, UFT will treat them differently as each action has its own local repository.

Components of Local object Repository

If you open the Local object Repository, the first thing you notice the action drop down. As the local object repository is a private property of an action, you have to select an action to catch hold of the respective object repository.

Once you have selected the Action, you will get the test object tree. The lowest element of the tree is often referred to as an object. In general, every node of the tree is an object. Once you click on any node, you will get the object properties in the right-hand side.

The Object details pane will have:

  1. Name- Object Identifier- Name of the object
  2. ClassName- Object Class name coming from add-ins or UFT/QTPs class selection mechanism. This field is not editable.
  3. Repository- Local- The location of the Object Repository. This field is not editable too. It just tells where the object is in the repository.

Now the lower pane shows the Object details:

Description Properties:

Each object comes with mandatory properties and assistive properties. By default UFT/QTP provides some properties here, but we can customize this as per our need.

  •    NativeClass-Edit
  •    Attached Text- The attached text retrieved from the application.

Visual Identifier- You can use it to enhance the object identification. That may reduce the chance to wrong object identification. This can be used to identify the object relative to other nearby objects.

  • Visual relation Identifier- Visual Identifier or visual relation identifier settings
  • Ordinal Identifier- Ordinal Identifier if any- mostly Type and value
  • Additional details- Enable smart identification
  • Comment

Advantage of local object repository:

  1. It is not an overhead.
  2. Very Fast.
  3. Object conflict will not occur.
  4. Objects can be edited from the repository only

The drawback of local object repository:

  1. Difficult to maintain
  2. The duplicate entry of Objects to a repository is possible.

How to add objects to the local repository?

You can record while interacting with the application, UFT/QTP will automatically add objects to the Object Repository. You can also add objects manually to the Object Repository.

How to Navigate:
  • Click Resource
  • Click on Object Repository
  • Click on Objects
  • Click on Add objects to Local
  • Show the object
  • Click ok
OR Filter to add object
OR Filter to add object

You may also get three options to filter from

  1. Only selected object(adds the selected object)
  2. Selected Object and its all its direct children
  3. Selected Object and all its descendants
How to add Objects repositories to an action?

if we miss to add object during recording time but we need that we can add objects using add object feature. We can also work with object spy to identify the required object.

How to rename the object in the local object repository?

We can rename the object in the object repository. Navigation will be as below:

  1. Click on Resources
  2. Click on Object repository
  3. Select the object which you want to rename
  4. Right click on that object
  5. Rename
  6. Type the correct name
  7. Select some other object

It will automatically rename the previous object.

Object Repository view Local
Object Repository view Local
How to delete objects from Object repository?

We can delete the object in the object repository. Navigation will be as below:

  1. Click on Resources
  2. Click on Object repository
  3. Select the object which you want to delete
  4. Right click on that object
  5. Click delete
  6. Click on confirm delete option
  7. Close repository.

Shared Object Repository

It’s central storage where the object information associated with multiple tests can be stored. So a Shared object repository is shared resource among multiple actions. After creating the repository we should associate that repository to your action and then perform Testing. This is another important thing to learn on object repository in UFT with examples.

Object Repository Manager can be used for this. The file extension is .tsr (Test shared repository). When we associate a shared object repository, we make the test asset available to the local action.

Export Local object to Shared Object
Export Local object to Shared Object

User (Test Engineer) creates a shared repository by adding objects. That can be shared among the number of tests. Using this method user can perform modifications on objects easily Navigation:

  1. Go to Resource
  2. Go to the Object repository manager
  3. Select Object
  4. Click on Add Objects
  5. Show the window/objects
  6. Click ok or File->Save
  •          The selected object only–It stores only one object
  •          Default object types–It stores all default objects
  •          All objects types–All default objects with static objects
  •          Selected object types–It stores objects along with Object class. in this case, we can add more class.

Step-1&2

Locate shared Object repository
Locate shared Object repository

Step-3

Add Objects to Shared Object Repository
Add Objects to Shared Object Repository

 

Step-6 Save a Shared Object Repository

Save Shared Object repository
Save Shared Object repository

Notes on Shared Object Repository:

  • You can not add an object to the shared object repository if the object is already present.
  • You can not add a checkpoint to the shared object repository.
  • You can certainly export the shared object repository to an XML file or Excel file.
  • You can merge one shared object repository to other shared object repository. This will create a 3rd object repository containing elements of both shared objects repositories contents.
  • You can add multiple test objects by enabling the option to Navigate and Learn.
  • You can not add output values to the shared object repository.
  • You will get a question mark if you have not installed properly add-ins in your machine. This also happens if the proper environment is not installed on your machine.

Advantage of shared object repository:

  1. Easy to update hence easy to maintain.
  2. Consumes less memory as we can avoid multiple copies of the same object.
  3. Highly reusable.

The disadvantage of shared object repository

  1. Object repository size will be huge
  2. Execution will be slow if the shared object repository is too big.
  3. Object conflict needs to be handled properly.
  4. Many test engineers may use shared object repository, hence it is very tough to edit concurrently.
  5. any change in the shared object repositories will affect the associated test case.
  6. In case of property identification, if UFT/QTP does not get proper match, it will activate smart identification that may also slow down the execution.

When to use Shared Object Repository?

When we know that the application is not stable and may change it’s object or object properties frequently (and we do not want to use descriptive programming),it makes sense to use shared object repository. We need to change in one place and that can reflect in all other test dependant on the same shared object repository.

How to make shared Object repository editable?

This is another important thing to learn on object repository in UFT with examples.

We have to open Object Repository Manager- another tool which enables us to make shared object repository editable.

  1. Click on Resource
  2. Go to the Object repository manager
  3. Click on File
  4. Click on Open
  5. Click on the browse button to browse path of the repository file
  6. Select file
  7. Enable editing

How to rename the object in the shared object repository?

  1. Click on Resource
  2. Go to the Object repository manager
  3. Click on File
  4. Click on Open
  5. Click on the browse button to browse path of the repository file
  6. Select file
  7. Enable editing
  8. Select object
  9. Right click on the object
  10. Choose rename
  11. Change the name
  12. Click on the other object
  13. The last object name automatically changed
  14. Save the file
  15. Close repository manager
Enable editing for shared object
Enable editing for shared object

How to delete the object in the shared object repository?

  1. Click on Resource
  2. Go to the Object repository manager
  3. Click on File
  4. Click on Open
  5. Click on the browse button to browse path of the repository file
  6. Select file
  7. Enable editing
  8. Select object
  9. Right click on the object
  10. Choose delete
  11. Confirm deletion
  12. Save the file
  13. Close repository manager.
Options after Enabling Shared repository
Options after Enabling Shared repository

 

Priority Logic for repository selection

This is another important thing to learn on object repository in UFT with examples.

In case one local object repository and one shared object repository has the same object

In case an object is mentioned in the Local object repository and shared object repository, during execution the corresponding action will give priority to Local object repository and pick up values from there to identify the object.

In case two shared object repositories have the same object

In this case, it depends on the sequence of association. In case the first repository is associated before the second one, the action will consider the first one. Just in case the first object repository is associated after the second object repository, the action will pick up the second one.

Can we change Local object repository to shared object repository or vice versa?

Yes, we can!!. we can switch between local object repository or shared object repository at any given point of time. The navigation is Test->Settings–>Resources

Here we have to choose as per our need. This is called switching of the repository.

When to use a Shared Object repository?

In case we are in a large project and many test engineers are working on different functionalities but use the same object, in that case, it is good to use Shared Object Repository. This is another important thing to learn on object repository in UFT with examples.

How to associate the shared object repository to the UFT/QTP test?

We can associate the shared object repository in three different ways:

Associate Shared Object Repository to test
Associate Shared Object Repository to test
Select Shared Repository to Associate
Select the Shared Repository to Associate
Step-1 Using code:

This is the most favorite and convenient way to associate object repository to a test. The code is as follows:

repositoriesColleaction.add "path&repositoryName"
Step-2 Using Action Property
  1. Go to Expert view
  2. Right click on Expert view of UFT/QTP editor
  3. Select Action
  4. Click on Action properties
  5. Click on Associate Repository
  6. Click on Add
  7. Provide path and identify the repository(You can also use the browse button to do the same)
  8. Click on Open
  9. Click on OK
Step-3 Using Associate repository
  1. Click on Resource
  2. Click on Associate Repository
  3. Click on Add
  4. Provide path and identify the repository(You can also use the browse button to do the same)
  5. Click on Open
  6. Associate with the target Action
  7. Click on OK

What is the difference between Local object repository and a shared Object repository?

This is another important thing to learn on object repository in UFT with examples.

Local Object RepositoryShared Object Repository
Local object repository is associated by default to an action we create.We have to explicitly associate a shared object repository
to one or more actions.
Local object repositories are locally editable.Shared Object repositories are by default read-only. We have
to edit shared object repository by Object Repository Manager
Nobody except the action owner can edit Local object repository.Shared object repository can be edited by anybody.
Extension of local object repository is .mtr and stored in a .bdb fileExtension of the shared Object repository is .tsr
Local Object Repository is useful when a few tests are working on a screen.Shared Object repository is useful when multiple tests are using a particular screen.
Renaming the Object in Local object repository does not affect any other script.Renaming the Object in Shared object repository may have serious failures in other scripts
Changes to Local object repository are local hence all scripts need to be changed in case object changes.Changes to Shared object repository are global hence changes reflect in all scripts.
Mostly no risk associated while working on Local object repository.The shared object repository may grow big and regular backup is required in
order to avoid corruption to the file.

What are the advantages and disadvantages of having an Object Repository?

This is another important thing to learn on object repository in UFT with examples.

The advantages of having an Object Repository

  • Sync with GUI front end of the application.
  • Highlight capability makes easier to Crosscheck.
  • During it is very easy to identify which object gets changed.
  • If it stores with the logical name of the object, it is extremely easy to maintain the OR file.
  • Scripts are untouched if the object property gets changed. we need to check the OR file that’s it!!
  • Modern scripting tools allow modifying the OR file separately.

The disadvantages of having an Object Repository

  • you need to check out the file size.
  • Object conflict may occur when adding individual OR files.
  • Sometimes extra objects get added and it makes the OR file heavy in size.
  • The OR files are private to the scripts. So concurrent update to the file is not possible
  • It became overhead while developing large projects.
  • Even though I like to use OR..but I cannot say descriptive programming is not required. Can you???
  • There are many things which can not be recorded. like-Sub Menu, Objects changing its position

How objects are stored in UFT or QTP?

It is a collection of objects stored in the XML file. Objects will have their own properties by which QTP/UFT will identify the objects uniquely. During recording, this entry to this file is automatically done by QTP /UFT. This is another important thing to learn on object repository in UFT with examples.

Object Repository is a place for scripts to store information/properties about objects. Object repository is maintained in XML format. It is the place where UFT stores all information what it learned during the recording phase. It contains

  • name
  • set of identifiers
  • object description

This information can be dependent on how UFT is going to recognize an object uniquely. They may differ from instance to instance, objects to objects.

Object repository is a tree view that shows the components in the current action, test or script.

It enables us to view or modify the test objects or add a new one.

The values populated here the default properties. UFT internally verifies and determines the classification of the object class. If the default properties are not enough to identify the object uniquely, UFT keeps adding other supportive properties like assistive properties or special identifiers(ordinal) to accomplish the goal.

The entry will have a logical name about the object and physical description about the object in the right side pane. We can perform several operations:

  • Rename the logical name.
  • Moving objects from one hierarchy to others
  • Change the object description
  • Delete object
  • Highlight selected object
  • Locating an object
  • Update physical description
  • Filtering object etc.

Overview:
Most of the objects,we encounter day by day,may have few or may have many properties.For better understanding let us sat properties as attributes.But when it comes for recognizing objects via QTP/UFT.Qtp recognizes object using 2 0r 3 important properties.
Before QTP really understands the object,It has a mechanism to set the context.Context is nothing but to help QTP to identify the application under test. We set this context via Add ins. Add ins give QTP the correct files to be loaded to identify the objects properly.
Qtp has default object identification configuration for every environment, if we feel that configuration is not sufficient for recognizing objects in our application, we can configure some more

Object Identification Types
a)    Normal identification

1)   Mandatory properties
2)   Assistive properties

b)    Smart identification

1)    base filter properties
2)    optional filter properties

c)    Ordinal identifier

1)    location
2)    index
3)    creation time(only for browser)

QTP learns information in the following in case of normal identification:

First of all the qtp learns all the mandatory properties at a time and tries to identify the object, with these properties uniquely.If it feels sufficient then it stops learning.If otherwise,it learns first assistive property and once again stops and tries to identify the object.like this qtp learns all requierd properties one by one. If the list of properties are enough to identify an object uniquely.It just stops.Now there might be situation,where, with all the assistive properties,QTP is not able to identify an object uniquely. Then QTP goes to Ordinal Identifier.

QTP learns information in the following in case of Smart Identification:

Smart identification is an optional feature, if we feel normal identification is not sufficient for any object, and then we configure Smart Identification for that object, in order to avoid Ordinal Identifier.
After normal identification if qtp feels not satisfied then it goes to smart identification. in smart identification 2 types of properties available, first qtp learns all base filter properties at a time and tries to identify the object uniquely. If it feels sufficient, then it stops learning otherwise it goes Optional Filter Properties and learns one by one. Still it feels not satisfied finally it goes to Ordinal Identifier.

Ordinal identifiers:

There are 3 types of ordinal identifiers available

1) Location: is based on object location in the AUT ,location starts from zero,Zero(x,y coordinate)
2) index: it is based on sequence of the programs, index starts from zero
3) Creation time: it is based on loading time of the web objects. qtp generates 0,1,2 like numbers.

Tool Settings Globalization:

As QTP is a I-tier(Stand-alone) application,making Tool settings globally is not possible.
For making tool settings global, QTP is providing a special feature called “Generate Script”.

STEPS:

1) Settings available in 3 areas.
a) File->Settings
b) Tools->Options
c) Tools->Object Identification

2) Perform required settings and generate Scripts
3) Share Script files to team members and ask them to execute those scripts.

What is the advantages of XML format export option?

You can modify the object properties without opening UFT/QTP tool. Your favorite XML editor can open the object repository and enable you to change the objects.

How Object repository can affect execution performance?

There are several approaches in the market to generate your script and the framework implementation. But we need to think a manner where script development time, script maintenance time becomes less. Most importantly we need to find an approach where the execution time also becomes less. This is another important thing to learn on object repository in UFT with examples.

What is the importance of downing the execution time?

Well, I am inspired by a philosophy that automation test engineers should not lose time by executing the test script. All the test script should be configured once and should be able to run unmanned manner.

Moreover, these scripts will run in a computer-assisted environment. The computer is not that intelligent as we are. If you insert enough intelligence into the script it might slow down the process and on the other side intelligence is less.

There is a chance that the script will error out. So what are the best approaches to automate your script that will serve long without issue is a question?

Object repository is a place where your testing tool uses to store information about objects under test for flow. This may be the .tsr file or a straight XML file. During the run, time script takes reference to this file and identify the objects.

It is seen if the OR size is less that means test engineers are doing more descriptive programming. Descriptive programming is very powerful but it is a time-consuming process. Hence it will slow down the process.

On the other hand, if the OR file is big. The seek time will be high. There might be a scenario where object conflict will occur. This also slows down the process.

Here this picture shows if OR files grow high in Size how the response time of the scripts increases.

As per experience, An O.R file should be between 5 to 12 MB..Above that or below that performance is not as good as we expected to be.

How to Load Object Repository Dynamically in QTP/UFT?

When automation test engineers design a framework, always the target to run the script uninterruptedly. Even if entry-level record and framework need an uninterrupted run!!! So for uninterrupted flow execution, one important aspect is to choose and execute a set of predefined scripts. Sounds good!!! This is another important thing to learn on object repository in UFT with examples.

Automation test engineers tried a lot and succeed by using excel or data loading logic. Yes…the power of automation viz coding logic. Excel was having several columns along with an executable column.

Where automation test engineers use to mentioned like yes or no. Based on that value the framework uses to use to pick the correct row to execute which intern calls correct subscripts to run.

One more sophisticated way to run through batch execution. More can be found here

With this approach their ware flaws.
1. It was not dynamic enough.
2. It was very slow as the framework used to load all the object repositories at a time or used to load a shared object repository.
3. The execution was frequently struck by object identification errors.

In this article, I want to venture how an automation engineer team has overcome these problems.
Well, after analysis, automation engineers saw that if we can control the Object repository and supply the same as and when required basis to the framework, we will be able to solve the huge shared object repository.
This is kind of divide and conquers rule!!!.

From this concept, automation test engineers came up with the incorporation of dynamic object repository loading concept.
Let us look into the code…Here is a small function or a method that will load the Object Repository Dynamically.

Function Load_OR(sPath)
'/This is the path where the OR is situated.
'msgbox sPath
Set objnew = CreateObject("QuickTest.Application")
objnew.Test.Settings.Resources.ObjectRepositoryPath =sPath
Set objnew= Nothing
End Function

This function is written in QTP 8.2.Don’t Know if it can be used in QTP 9 and aboveboard the same but another technique is given below……The interesting point is the here the path is also dynamic.


Public Sub proAddRepository(ByVal strRepName)
Dim App
Dim qtRepositories
Set App = CreateObject("QuickTest.Application") ' Create the Application object
App.Launch ' Launch QuickTest
App.Visible = True ' Set QuickTest to be visible
Set qtRepositories = App.Test.Actions(Environment("ActionName")).ObjectRepositories
'If the repository cannot be found in the collection
If qtRepositories.Find(strRepName) = -1 Then
Wait(1)
qtRepositories.Add strRepName, 1
End If
Set qtRepositories = Nothing
Set App = Nothing
End Sub

Let’s see an example….


Dim qtApp 'As QuickTest.Application ' Declare the Application object variable
Dim qtRepositories 'As QuickTest.ObjectRepositories ' Declare an action's object repositories collection variable
Dim lngPosition
' Open QuickTest
Set qtApp = CreateObject("QuickTest.Application") ' Create the Application object
Set qtRepositories = qtApp.Test.Actions("Login").ObjectRepositories ' Get the object repositories collection object of the "Login" action
' Add MainApp.tsr if it's not already in the collection
repositorypath=InputBox("Enter the abosolute path along with the Repository name to attache")
If qtRepositories.Find(repositorypath) = -1 Then ' If the repository cannot be found in the collection
qtRepositories.Add repositorypath, 1 ' Add the repository to the collection
End If
' Set the new object repository configuration as the default for all new actions
qtRepositories.SetAsDefault ' Set object repositories associated with the "Login" action as the default for all new actions
'Save the test and close QuickTest
qtApp.Test.Save ' Save the test
qtApp.Quit ' Quit QuickTest
Set qtRepositories = Nothing ' Release the action's shared repositories collection
Set qtApp = Nothing ' Release the Application object

The code has placed the automation one step further. The framework has been improved.
Shared object repository concept has been removed forever!

How to Convert the test shared repository to XML in AOM or VBScript?

Below is the code to convert the test shared repository to XML: This is another important thing to learn on object repository in UFT with examples.

Set myObj=CreateObject("Mercury.ObjectRepositoryUtil")
myObj.ExportToXML([source of the .tsr file],[destination of the file])
like-
myObj.ExportToXML "C:\test\demo.tsr","C:\test\demo.xml"
set myObj=Nothing

Alternatively, you can export using the object repository Manager
Path:
Resources –>Object Repository Manager
File ->open to open the .tsr file
File ->Export to XML

The above-written solution works fine from UFT/QTP but fails when we save this code as.VBS file with an Error code- “ActiveX component can’t create the object, Mercury.ObjectRepositoryUtil”

Error code-800A01AD

How to Resolve this?
  1. Open Command prompt
  2. type %System Root%\syswow64\csscript\[path of the script]
  3. Click enter

This works great!! But this only works if you have UFT installed on your machine. Just in case, you move your test script to another machine where the UFT is not present, the script will fail.

The exact issue has been listed in StackOverflow. User 2034602 has given a possible solution for this.

  • Register RepositoryUtil.dll with REGSVR32
  • Use CSSCRIPT.exe under syswow64 to run the script.

How to export a shared object repository to Excel?

In his blog post qtpsudhakar has shown a nice way to export object repository to excel. This is another important thing to learn on object repository in UFT with examples.

'############################################
'Description  : Exporting Object Repository to Excel
'What Concepts used : Object Repository Model, Excel Object Model
'Required Parameters: Object Repository, Excel Path (Creates Excel File)
'Required Software : QTP/UFT Installed
'Developed By  : Sudhakar Kakunuri
'Modified By: Animesh
'############################################

'Declare Variables
'************************************
Dim srcRepository
Dim ParentObject
Dim excel, workbooks, rIndex, objRange
Dim ObjectRepositoryPath,orExcelPath
'************************************

'Specify file Paths
'************************************
'OR must be created before executing this
'You can use .TSR, .XML and .BDB Object Repositories
'An excel file will be created automatically with the name excel.xls
ObjectRepositoryPath="C:\Test\OR\createrequest.tsr"
orExcelPath="D:\excel.xls"
'************************************

'Load Object Repository
'************************************
'Creating Object Repository  utility Object
Set srcRepository = CreateObject("Mercury.ObjectRepositoryUtil")

'Load Object Repository
srcRepository.Load ObjectRepositoryPath
'************************************

'Create Excel file with columns, colors and Autofit
'************************************
'Create Excel Object  
Set excel=createobject("excel.application")   

'Add New Workbook  
Set workbooks=excel.Workbooks.Add()

excel.Cells(1,1).value="ParentObjectLogicalName"
excel.Cells(1,2).value="ParentObjectProperties"
excel.Cells(1,3).value="ObjectLogicalName"
excel.Cells(1,4).value="ObjectProperties"

Set objRange = Excel.Range("A1:D1")

objRange.Font.Bold = True
objRange.Font.ColorIndex = 1
objRange.Interior.ColorIndex=15

' rIndex variable used to enter values row by row
rIndex=2 
'************************************

'fnExportORtoExcel will get objects and properties from OR
'************************************
'Calling a fnExportORtoExcel Function
fnExportORtoExcel ParentObject
'************************************

'Auto Fit all other columns & save excel
'************************************
'Autofit all columns
excel.Worksheets("Sheet1").UsedRange.Columns.AutoFit

With excel.Worksheets("Sheet1").UsedRange.Borders
        .LineStyle = 1
        .Color = vbblack
        .Weight = 2
End With
    
'Save Work Book  
workbooks.saveas orExcelPath,true 

'Close Work Book  
workbooks.Close  
  
'Quit from Excel Application  
excel.Quit  
'************************************

'Release Variables  
'************************************
Set workbooks=Nothing  
Set excel=Nothing  
Set srcRepository=Nothing
'************************************
msgbox "Exporting Completed. Open "&orExcelPath&" to view the Excel Object Repository"

'************************************

Function fnExportORtoExcel(ParentObject)

'Get Objects by parent From loaded Repository
'If parent not specified all objects in OR will be captured

Set fTOCollection = srcRepository.GetChildren(ParentObject)

    For RepObjIndex = 0 To fTOCollection.Count - 1

        'Get object by index
        Set fTestObject = fTOCollection.Item(RepObjIndex)

  Props=""
  
            'Check whether the object is having child objects
            If srcRepository.GetChildren (fTestObject).count<>0 then


                    'Get TO Properties List
                    Set PropertiesColl=fTestObject.GetTOProperties
       
                    For pIndex=0 to PropertiesColl.count-1
           'Store properties in a variable with a comma delimiter
                                Set ObjectProperty=PropertiesColl.Item(pIndex)
                                Props=Props&","&ObjectProperty.name&":="&ObjectProperty.value
                                
                    Next
    
    If InStr(1,Props,",")=1 Then
     Props=Mid(Props,2)
    End If
    
    
                'Write Logical name and Properties in Excel Sheet
    excel.Cells(rIndex,1).value=srcRepository.GetLogicalName(fTestObject)
    excel.Cells(rIndex,2).value=Props
    
    'Color the cells based class name
    If InStr(LCase(Props),"micclass:=browser")<>0 Then
     Set objRange = Excel.Range("A"&rIndex&":B"&rIndex)     
     objRange.Font.Bold = True
     objRange.Font.ColorIndex = 1
     objRange.Interior.ColorIndex=36 
     
    ElseIf InStr(LCase(Props),"micclass:=page")<>0 Then
     Set objRange = Excel.Range("A"&rIndex&":B"&rIndex)     
     objRange.Font.Bold = True
     objRange.Font.ColorIndex = 1
     objRange.Interior.ColorIndex=35

    ElseIf InStr(LCase(Props),"micclass:=frame")<>0 Then
     Set objRange = Excel.Range("A"&rIndex&":B"&rIndex)     
     objRange.Font.Bold = True
     objRange.Font.ColorIndex = 1
     objRange.Interior.ColorIndex=40
    End If    

    'increase rIndex to enter data in next lines of excel
    rIndex=rIndex+1
    
    'Calling Recursive Function
                fnExportORtoExcel fTestObject

            else
              'This else block will execute when the object is not having any childs

     'Get TO Properties List
                    Set PropertiesColl=fTestObject.GetTOProperties
                    For pIndex=0 to PropertiesColl.count-1
                       'Store properties in a variable with a comma delimiter
                                Set ObjectProperty=PropertiesColl.item(pIndex)
                                Props=Props&","&ObjectProperty.name&":="&ObjectProperty.value
                    Next
                
    If InStr(1,Props,",")=1 Then
     Props=Mid(Props,2)
    End If
    
                'Write Logical name and Properties in Excel Sheet
    excel.Cells(rIndex,3).value=srcRepository.GetLogicalName(fTestObject)
    excel.Cells(rIndex,4).value=Props
    
    'increase rIndex to enter data in next lines of excel
    rIndex=rIndex+1
            End if
    Next

End Function
'************************************

How to Insert Web Service Test Objects to the Object Repository?

In order to add web service objects, we need to enable web service to add in. Once the web service add-in is enabled, we can now add web service objects to the Object Repository.

Once we have successfully added web service objects, we will be able to access all its supported operations. These operations can be seen in the expert view (Intellisense or Step generator) in keyword view under the operations column.

Steps to insert Web service Test Object to the Object Repository

  1. Navigate to Repository toolbar button(Resource-> Object repository)
  2. Navigate to web service add object button.
  3. Specify the web service add object button.
  4. Specify the WSDL(if you want WSDL automatic screening and automatic object addition)
  5. Specify the service screen-selective service to create the test object.

How to compare two Object Repositories?

UFT/QTP provides object repository comparison tool to find out the difference between objects of two different repositories. This is another important topic to learn object repository in UFT with examples.

Steps to compare two object repositories:

  • Go to Resource
  • Click on Object Repository Manager
Object repository comparison tool
Object repository comparison tool
    • Click on Tool
    • Click on Object Repository Comparison Tool
Object repository comparison tool Option
Object repository comparison tool Option
    • Once the comparison tool opens
    • Provide the first file and second file along with the path(you can also choose to click on browse button to locate the object repository files)
Object repository comparison OR Options
Object repository comparison OR Options
    • Click on OK
    • The tool will compare the objects and displays the result as an easy human-readable way.
Object repository comparison report
Object repository comparison report
  • You can also use three filter properties.

The filter properties are as follows:

  1. Identical Objects
  2. Unique Objects
  3. Partial matched Objects

How to Merge two Object Repositories in UFT/QTP?

UFT/QTP provides another important tool to merge two repositories. The name of the tool is Object Repository Merge Tool

Steps to merge two repositories

  • Go to Resource
  • Click on Object Repository Manager
Object repository comparison tool
Object repository comparison tool
  • Click on Tools
  • Click on Object Repository Merge Tool
Object Repository Merge Tool
Object Repository Merge Tool
  • Once the Merge Tool window opens provide the primary file and secondary file along with the path.(You can choose to click on the browse button to locate the files)
Object Repository Merge Tool-comparison box
Object Repository Merge Tool-comparison box
  • Click on OK
  • The tool will merge and provide the result in a human consumable way.

You can also use filter properties like

  1. Show all objects
  2. Show only conflicting objects

When you merge objects from two different sources(two different repositories), UFT/QTP will create a third repository containing all pieces of information. This will ensure the source repositories are unchanged and no unwanted data goes inside them.

How do we get conflict during Object Repository Merge?

While merging two object repositories, If UFT/QTP determines two objects with the same name and same test object class but their descriptions are different, UFT/QTP will highlight the object in the repository and declare it as conflict.

second possible cause is if two objects have the same name but different contents and they belong to different repositories.

The third possible cause is if two objects have different names and their properties are the same but they belong to two different repositories.

The last well-known cause of merge conflict if the two objects have the same name but few of their properties are also the same but not all. In that way, they look identical but actually, they are not.

If you get conflict, you need to manually resolve the conflicts.

Do not worry if you have to manually resolve it. UFT/QTP will also provide possible solutions for conflict resolution.

How to export local object repository to the shared object repository?

  1. Open object repository window. Select Action as Local Object repository is private to Action.
  2. Now Select Object Repository
  3. Go to file
  4. Export local objects
  5. Select location
  6. Click on save

This will export the local object repository to the shared object repository.

Can we update the shared object repository from the local object repository?

There are the below ways to update the shared object repository from the local object repository:

Way-1- The best way

  • Do not open any test.
  • Open object repository manager
  • Click on Tool
  • Click on Update from the Local repository
  • Choose the test, who’s Local object repository needs to be referenced.
  • Update the selected object or update all.
  • Click on Save

This will automatically pull all local objects to shared objects repository.

Way-2 By clearing the read-only checkbox

  • Go to the Object Repository Manager.
  • Clear the read-only checkbox- clear the lock
  • Create a new test(A new local object repository will  be attached to the test.)
  • Associate a shared object repository into the test.
  • Update the local object repository by adding new items to it or modifying properties of an existing item.
  • This will enable you to update the shared object repository from the local object repository.

Export local objects vs export and replace vs local objects vs copy objects to local

If we choose to export local objects, the local objects are exported to .tsr file. it is not associated to any test. So if any test is executing, it keep referencing to old object repository.

If we choose to export and replace local objects, the newly created shared object repository(.tsr) file is associated to our test. The current object repository becomes out of order (in other words, it is deleted).

The only issue with this approach is that new enforced shared object repository can not be edited. Our current test starts referring the new shared object repository file(.tsr).

Copy Objects from shared repository to the local object repository lets us use the older repository file with updated contents from shared object repository.

While mapping repository parameters, what if you have more than one repository parameter with same name in different shared object repositories that are associated with the same test?

Before you map repository parameters, if you have more than one repository parameter with same name in different shared object repositories that are associated with the same test, the repository parameter from the shared object repository with the highest priority is used. After you map the repository parameters, UFT/QTP uses the mapping you have defined. In addition, changing the priority or default values has no effect after the parameters are mapped.

Good read- What to do if UFT/QTP does not recognize the object?

Please visit this website to understand what should you do if UFT/QTP does not recognize the objects.

Is possible to write code without Object repository?

Yes, it is possible to write code without Object repository but in that case you have provided the properties in the code itself for an object.

What is Descriptive Programming in UFT?

Entering / Providing objects information directly into the test script is called Descriptive Programming. When QTP/UFT records any action on any object, it tries to identify the object with some of its properties. And stores them in an object repository. Later point of time, during execution, it takes reference from it and tries to find out the object in the application and perform a set of operations.

So, if an object is not present in the object repository, QTP/UFT can not identify the object and operate on it.
With the fast development of application and agile way of developing software advocates more about descriptive programming. Imagine we need to design our test script without the GUI. Yes!! it is possible.

Descriptive programming provides information to QTP/UFT bypassing object repository. The same object information is passed to QTP/UFT so that it can identify the object.

Let us think about a person whom we don’t know. When we meet for the first time, we create an image of that person. Like the name, tentative age, gender, height, if the person wears specs or not, etc.  For us to remember that persons these are enough. we will be able to identify the person in our next meet by using our stored properties of that person.

These are mandatory properties. There are some other things we can notice. We may also notice the shirt color, trouser color, some more details. They are assistive properties. Help to identify the person uniquely. But they may change.

What is Descriptive Programming in UFT??

Likewise, if we need to identify a textbox, the first thing we will be looking at is the name or id. This will help me to identify the textbox. In this method of script creation, we no need to have Object Repositories.
But assume that we have a special application that is dynamic. So with the stored object description QTP/UFT will not be able to identify the objects.

Say after logging we have a welcome message says Welcome <<UserName>>. Upon clicking on the username it will navigate to the actual page.

This will work fine if the same user logs in but fails when another user logs in as the stored object description does not match to the application object. So we need to find another way of coding.This is called Descriptive Programming.

In the real world, if the person says I want to meet you and I will be seating some coffee hose, table number-2. I will be in a redshirt. Then we will not try to find the person, directly go to that coffee house and go to table no-2. Now if I see a person with a red shirt, we will get the person. Is not it??

So, in this method, we provide information about the object to QTP and request it to perform search operations and carry out tasks.
In a real project, if the GUI is not available or the project size is getting bigger(OR will also bigger), we use descriptive programming.

When to use descriptive programming?

Apart from the above reason, there are few other situations when we need to opt for descriptive programming.  They are as follows:

  • Our object repository gets huge due to a large project. And larger the OR in size, it will impact the execution performance. Now to reduce dependency on OR, we can go for descriptive programming.
  • The objects in the application are dynamic and need special handling to identify the object. The best example would be of clicking a link which changes according to the user of the application, Ex. ” Logout < < UserName > > “.
  • When you don ‘ t want to use object repository at all. Modification to a test case is needed but the Object repository for the same is Read-only or in shared mode i. e. changes may affect other scripts as well.
  • When a webpage or an application is still not developed, that time, it is not possible to add the object directly from the application or UAT. In that case, we can still descriptive programming to generate our code by seeing the technical specification document.
  • Say we need to verify a table data. There are n numbers of data to verify. These n data are divided into say 20 pages. Each page contains the Next, the Previous button. So for 20 pages, there will be 20*2=40 button objects created. To avoid such huge object creation, we can use descriptive programming.
  • If there are n numbers of textboxes present inside a UAT. in that case only value changing is the index of the textboxes. Say for first text box the name is text_1 and for second textbox the name of the textbox is text_2 and so on. In such a condition, adding them to an object repository is not a feasible option. Descriptive programming can be really helpful.
  • If the same page of UAT is getting changed due to customer specification and being an automation engineer we can insert all possible variations into different object repositories. Now by coding, we can load and unload the shared object repository based on the customer scenario. But this changing may impact long execution. To minimize this risk, we can go for descriptive programming.

Advantages of Descriptive programming:

  • Descriptive Programming based Test scripts are faster in execution than Repository based Test scripts.
  • Scripts are portable (we can run these scripts from any machine easily).
  • Maintenance is easy (less amount of resources).
  • We can start the Test Execution process even though the Application is not ready.

Descriptive programming is 2 types.
1. Static Programming-By describing the form of the string arguments.
2. Dynamic Programming-By creating properties collection object for the description.

Static Programming

In this style of script generation, we provide objects information directly into the script.
Ex:


Invokeapplication "C:Program FilesHPQuickTest Professionalsamplesflightappflight4a.exe"
dialog("text:=Login").Activate
dialog("text:=Login").Winedit("attached text:=Agent Name:").Set "asdf"
dialog("text:=Login").Winedit("attached text:=Password:").Set "mercury"
dialog("text:=Login").Winbutton("text:=OK","width:=60").Click

Note:
1. Dialog, WinEdit, and WinButton – Test Objects
2. text, attached text – Property names
3. Login, Agent Name: Password: OK – Property values or Logical Names of the Object
4. Activate, Set, Set secureSetsecure, Click – Methods
Note2:
If we feel one property information is not sufficient for recognizing the object uniquely, then we can provide more properties information by separating with commas.
Note 3:
If we want to get objects information (Test objects, properties, and values), we can use object spy features. This feature is available in Tools Menu, in the local repository, and repository manager.
——————————————————————-
If we want to maintain ‘Objects information’ in a centralized location then we can use Constants.
Steps:
Creating Constants:

Const Login="text:=Login", Agent="attached text:=Agent Name:"
Const Pwd ="attached text:=Password:", Ok="text:=OK"

Note: we can declare no of Constants in a line by separating with Camas (,), if we take another line then we have to use Const Statement again.
Creating a Library file
Place Constants in Notepad and save as .vbs file
Associate the Library file to QTP (File->Settings->Resources-> Click add (+) icon-> Browse path of the Library file->Click Apply and click Ok buttons
Otherwise, we can load the library file during run-time
Syntax:
execute file “Path of the Library file(.vbs)”
After that create the Test Script using Constants
Creating the Test Script using Constants:


Invokeapplication "C:Program FilesHPQuickTest Professionalsamplesflightappflight4a.exe"
Dialog("Login").Activate
Dialog("Login").Winedit("Agent").Set "asdf"
Dialog("Login").Winedit("Pwd").Set "mercury"
Dialog("Login").Winbutton("Ok").Click

we can describe an object directly in a statement by specifying property:=value pairs describing the object instead of specifying an object’s name. The general syntax is:


TestObject("PropertyName1:=PropertyValue1", "... ", " PropertyNameX:=PropertyValueX")
  • TestObject – the test object class could be WebEdit, WebRadioGroup, etc..
  • PropertyName:=PropertyValue- the test object property and its value.

Each property:=value pair should be separated by commas and quotation marks. Note that we can enter a variable name as the property value if we want to find an object based on property values we retrieve during a run session.

Consider the following example

<INPUT type = "textbox" name = "txt_Name">
<INPUT type = "radio" name = "txt_Name">

Now to refer to the textbox the statement would be as given below

Browser("Browser").Page("Page").WebEdit("Name:=txt _ Name", "htmltag: =INPUT"). set "Test"

And to refer to the radio button the statement would be as given below

Browser("Browser").Page("Page").WebRadioGroup("Name:=txt _ Name", "htmltag: =INPUT"). set "Test"

If we refer to them as a web element then we will have to distinguish between the two objects using the index property

Browser("Browser").Page("Page").WebElement("Name:=txt _ Name", "htmltag: = INPUT ", " Index: = 0 ").set " Test " //Refers to the textbox
Browser("Browser").Page("Page").WebElement("Name:=txt _ Name", "htmltag: = INPUT ", " Index: = 1 ").set " Test " //Refers to the radio button 

Advantages:
If we maintain Object Information in the centralized location, then we can handle modifications easily.
——————————————————————-

Dynamic Programming:

In this style of script generation, first, we create description objects, provide properties information and use description objects in the test script. To use this method we need first to create an empty description. Then add filters accordingly.

When we use a property name for the first time the property is added to the collection and when we use it again the property is modified. By default, each property is defined as a regular expression.

Creating Properties Collection Objects


Set oLogin=description.Create
Set oAgent=description.Create
Set oPassword=description.Create
Set oOk=description.Create
//Entering Properties Information into Objects
oLogin("text").value="Login"
oLogin("width").value=320
oLogin("height").value=204
oAgent("attached text").value="Agent Name:"
oPassword("attached text").value="Password:"
oOk("text").value="OK"
//Generating Tests using Properties collection Objects
Invokeapplication "C:Program FilesHPQuickTest Professionalsamplesflightappflight4a.exe"
Dialog(oLogin).Activate
Dialog(oLogin).Winedit(oAgent).Set "asdf"
Dialog(oLogin).Winedit(oPassword).Set "mercury"
Dialog(oLogin).Winbutton(oOK).Click

Note1: Create Description objects and put into one library file, by associating that library file, we can generate tests.
Note2: Dynamic programming is some difficult in preparation than static programming but maintenance is very easy.
In this style of script creation also, we can maintain Objects information in the Centralized location by putting collection objects in a Library file.

How to get child objects by using description?


Set objDesc=Description.Create
objDesc("htmltag").value="input"
objDesc("name").value="abc"
Set allChilds=Browser("Browser").Page("Page").ChildObjects(objDesc)
for each child in allChilds
child.set "Test"
Next
//or
for i=0 to allChilds.count-1
allChilds(i).set "Test"
Next

Descriptive Programming is an advanced concept of QTP coding. Testers can handle the application without using the OR by implementing Descriptive programming.

Can we add a description dynamically?

Yes, we can add multiple descriptions dynamically using code. In the above code, the snippet objDesc.count will return how many filters we are using in the collection. we can also dynamically add and delete descriptions (filters) to the collection.

Set objDesc=Description.Create
//for addition
objDesc.add("htmltag","input")
objDesc.add("name","abc")
//for deletion
objDesc.delete("htmltag")

How do I check if the property exists or not in the collection?

The answer is that it’s not possible. Because whenever we try to access a property that is not defined it’s automatically added to the collection. The only way to determine is to check its value that is use an if statement.

if obj.ChkDesc ("htmltag").value = empty then 
Advantages::
    • They are reusable
    • Modification of the script becomes easy in compare to QTP Code
    • This is very useful when applications are not available
    • It is flexible for the high performance of the application.
    • This is a very speedy technique for execution
    • It can effectively handle the object implementation problem of an application.

Disadvantages: If the property values change, it is necessary to upgrade the description. So maintenance is an issue for descriptive programming.

Few Common Example of Descriptive Programming:

How To Count The Numbers of Links On A Page and click on a link in QTP/UFT?

This is a very common scenario when automating a webpage. Say on a webpage I need to check if a particular link is available or not. Or there might be a scenario when you need to click on a particular link which is generating dynamically.

If it is static then you can record and do. But which is dynamic, for them we need to implement artificial intelligence. Before we go ahead and code…Let us think about the logic. Logic Well, when we write a code for a link we use to write like this……

< a href="xyz.com">Link Name1</a>
<a href="deb.com">Link Name2</a>

so through QTP if we can read the elements of a page and check if an “A” tag is there in the page element it will be surely a link. Isn’t it??
Code
So, all the links look the same. And they follow the same pattern. This is a small piece of code which will look like-


SystemUtil.Run http://www.yahoo.com/
Set aa=description.Create
aa("htmltag").value="A"
// This type of coding is called descriptive programming.
set bb=Browser("name:=Fun.*").Page("title:=Fun.*").childobjects(aa)
cc=bb.count
msgbox cc

There is another way to find out the count of the link


Set oDesc = Description.Create()
oDesc("micclass").Value = "Link"
//here we are filtering the object oDesc by its default class micclass. micclass of a link is "Link"
Set Links = Browser("Browser").Page("Google").ChildObjects(oDesc)
NumberOfLinks = Links.Count()
Msgbox NumberOfLinks
 

even, if, you need to click on a specific link you can modify the script little bit..say I have a link called yahoo.com and I need to click on the mail link.
Logic is again same …find out all the links
Now the extra is that we need to check if the link name is “Mail”. If so generate a click event.


SystemUtil.Run http://www.yahoo.com/
Set aa=description.Create
aa("htmltag").value="A"
'either specifying here
--------------------------------
aa("name").value="Mail"
-------------------------------
set bb=Browser("name:=Fun.*").Page("title:=Fun.*").childobjects(aa)
cc=bb.count
for i=0 to cc-1
if bb(i).getROProperty("name")="Mail" then//link name
bb(i).click
exit for
end if
next
 

How to check all checkboxes on a webpage/window in UFT or QTP?


Set a=Description.Create
a("html tag").value="input"
a("type").value="checkbox"
Set b=Browser("name:=").Page("title:=").childobjects(a)
c=b.count
msgbox c
For i=0 to c-1
b(i).set "on"
Next
 

How to Close All Browser from QTP/UFT Code?

Most of the time I have seen that we need to close Internet Explorer while testing through QTP. Internet Explorer means all the pop-ups, the main page. Say I am testing an application which needs to navigate different URL. So what we generally do is to open a browser do what we want to do and close it for the next set of a task may be in different URL.

A common test case maybe

1. Open IE and navigate to your HR link to create an employee.
2. After the creation of the employee, you need to close that and open another browser to register him to yahoo groups.
3. Now you need to open some websites called life insurance..fill up the data and employee number which is generated in Step-1.
4. Get the corresponding Policy number and again open the HR link to update employee information.

For such cases to avoid the problem of multiple IEs we use to open a URL perform some task and close it after saving it.
Here is a small code that will assist you to close an IE from QTP.


Sub CloseAllBrowsers()
Systemutil.CloseProcessByName("IEXPLORE.exe")
wait(5)
End Sub
 

Now you can do a further enhancement on this.
Say I have opened a meeting window and want to show my running window to our client or my seniors or there might be cases when I might open a test management tool like QC which runs on IE and want to run the test. So every time I will not be interested to open QC page.

This is a small modification on the code which will be helpful for such scenarios.


On Error Resume Next
Dim intWndCnt
Dim oDesc, oWnd
'Create Object description
Set oDesc = Description.Create '
Set oWnd = Desktop.ChildObjects(oDesc)
intWndCnt = oWnd.Count
For i = 0 to intWndCnt - 1
Set TmpObj = oWnd.item(i)
strTmpTitle = oWnd.item(i).GetROProperty("Text")
If instr(1,strTmpTitle, "Microsoft Internet Explorer",1) > 0 Then
If instr(1,strTmpTitle, "Mercury Quality Center",1) > 0 Then
'msgbox "Title :" & oWnd.item(i).GetROProperty("Text")
Else
'msgbox "Close : & oWnd.item(i).GetROProperty("Text")
oWnd.item(i).close
End if
End If
Next
'Clean up
Set oDesc = nothing
Set oWnd = nothing
 

How to Calculate Number of Opened Browsers in QTP/UFT?

Function Browser_Count()
Set objBrowser =description.create()
objBrowser("micclass").value="Browser"
Set sBrowsers=desktop.childobjects(objBrowser)
ibCount=sBrowsers.count
If ibCount<>0 Then
Browser_Count=ibCount
Else Browser_Count=1
End if
Set objBrowser=Nothing
Set sBrowsers=Nothing
End Function

How to Close Oracle Form in QTP/UFT??

This is one more situation that arises very common to an ERP test engineer. Most of the time we rely on QTP’s record feature. But this is a scenario that occurs all most in every window of Oracle ERP Testing.

So instead of doing record playback every time, I tried to use some descriptive approach to make it a general case. So this can be treated as a common function across the scenario. This is code rather sub/procedure where we need to pass the form name as a parameter and this will close the form.

Sub ERP_CloseForm(sFrmName)
If OracleFormWindow("short title:="& sFrmName).Exist Then
OracleFormWindow("short title:="& sFrmName).CloseForm
End If
End Sub

How to Get Browser Title in QTP or UFT?


Function GetBrowserTitle()
set sbrowser=Description.create()
' we are creating a blank object named as sbrowser.
sbrowser("micclass").value="Browser"
' we are assigning the sbrowser object as "Browser
set obj=Desktop.childObjects(sbrowser)
icount=obj.count
if(icount<>0) then
GetBrowserTitle=Browser("creationtime:="&icount-1).GetROProperty("title")
end if
Set sbrowser=Nothing
set obj=Nothing
End Function

How to Count Number of open Browsers in Desktop Using QTP/UFT?

This is another important concept in Descriptive Programming in UFT.

For this the concepts we will be using are:
1. ChildObject
2. Descriptive programming

with ChildObejct we will see how many objects are present under desktop as a child.
And with the description, we will determine if the child matches our description
This is the function that returns the no of browser count.


Function count_Browser()
Dim objDesc ‘As Description
Dim objBrowsers ‘As Collection
Set objDesc = Description.Create
objDesc(“micclass”).Value = “Browser”
Set objBrowsers = Desktop.ChildObjects(objDesc)
for l_BrowserIndex = 0 to objBrowsers.Count - 1
count_Browser=objBrowsers.Count 'returns no of browser
strTemp = (l_BrowserIndex).GetROProperty("hwnd")
strTemp = (l_BrowserIndex).GetROProperty("title")
Set objBrowser = Nothing
Next
count_Browser=strTemp 'returns the title
Set objBrowsers = Nothing
Set objDesc = Nothing
End function

When we use this function:
1. When we need to understand how many browsers present.
2. If we have to do certain operations with any of the browsers. Like- let the first browser be open but second needs to be closed.

 

Code to Close a particular Browser:


Sub CloseBrowser(iHwnd)
if browser("hwnd:="&iHwnd).Exist(3) then
browser("hwnd:="&iHwnd).close
end if
end Function
call CloseBrowser iHwnd
 

 

How to work with Editbox in UFT/QTP via descriptive programming?

Below is the Code related to EditBox.Frequently we need to get data from an edit box that is under a webpage and set the data to the box.This is another important concept in Descriptive Programming in UFT.
Below is the very popular code to Set and get data from the webpage.

Set obj=Browser(“ABC”).Page(“XYZ”)
You may create an object up to where it is necessary. (For more help …go to OR and check the hierarchy)
objname=Name of the edit box.

How to enter a value in the edit box


'FUNCTION : setWebEdit
'ARGUMENTS : obj,objname,entervalue
'DESCRIPTION : Enters value into webedit
Function setWebEdit(obj,objname,sValue)
If obj.WebEdit(objname).exist Then
If Not obj.WebEdit(objname).GetROProperty("disabled") Then
obj.WebEdit(objname).click
obj.WebEdit(objname).Set sValue
End If
End If
End Function

get properties of the edit box:


'FUNCTION : getWebEdit
'ARGUMENTS : obj,objname
'DESCRIPTION : Gets particular webedit's value
'RETURNS : value of webedit '**************************************************************************************************************
Function getWebEdit(obj,objname)
If obj.WebEdit(objname).Exist(5) Then
If Not obj.WebEdit(objname).GetROProperty("disabled") Then
obj.WebEdit(objname).click
getWebEdit = obj.WebEdit(objname).GetROProperty("value")
End If
End If
End Function

How to make the full screen a browser in UFT/QTP?

This small function will maximize the Browser.pls do an object spy and check the handiHwnd of the browser.This is another important concept in Descriptive Programming in UFT.


call maximize (iHwnd)
Sub maximize(iHwnd)
Browser("hwnd:="&iHwnd).Fullscreen
End Sub

How to get Tooltip in UFT/QTP

I was in a project where there was a peculiar requirement to capture tooltips through a script. I got several requests also to write a code that will capture the tooltips. I tried with Google!! I got a very nice thread of motevich.

I found this is a great solution. This also solves the problem of capturing the alt property of the Image. Here is a solution for capturing Tooltips of image. Even in my project, I have used this code only.This is another important concept in Descriptive Programming in UFT.


Dim descImage, listImages, attrAltText, attrSrcText
Browser("Main Page - Wikipedia,").Sync
Browser("Main Page - Wikipedia,").Page("Main Page - Wikipedia,").Sync
' Create description for all images on a Web page.
' For that we use "html tag" property and its value "IMG"
Set descImage = Description.Create
descImage("html tag").value = "IMG"
' Get all images which match the above description
Set listImages = Browser("Main Page - Wikipedia,").Page("Main Page - Wikipedia,").ChildObjects(descImage)
' Check tool tips of images
For i = 0 To listImages.Count - 1
attrAltText = listImages(i).GetROProperty("alt")
attrSrcText = listImages(i).GetROProperty("src")
If attrAltText <> "" Then
MsgBox "Image src: " & attrSrcText & vbNewLine & "Tool tip: " & attrAltText
End If
Next

How to Count, how many Buttons and Edit boxes available in Flight Reservation main window.

This code snipped is a mixture of OR and Descriptive programming. Till the navigation and reaching the main window, I have used OR and then I have used Descriptive programming. This is another important concept in Descriptive Programming in UFT.

Note: We can use a mixture of Descriptive and OR supported coding. But if we have started putting a description in the hierarchy, from then the OR support gets expired, we need to continue using Descriptive way to figure out the child objects.


If Not window("Flight Reservation").Exist (2) Then
SystemUtil.Run "C:Program FilesMercury InteractiveQuickTest Professionalsamplesflightappflight4a.exe"
Dialog("Login").Activate
Dialog("Login").WinEdit("Agent Name:").Set "bcroy"
Dialog("Login").WinEdit("Password:").Set "mercury"
Dialog("Login").WinButton("OK").Click
End If
Set oDesc = Description.Create() 
oDesc("micclass").Value = "WinButton" 
Set Buttons = Window("text:=Flight Reservation").ChildObjects (oDesc) 
Num_Buttons = Buttons.Count() 
Set oDesc1=Description.Create()
oDesc1("micclass").Value="WinEdit"
Set Editboxes=Window("text:=Flight Reservation").ChildObjects (oDesc1)
Num_Editboxes= editboxes.count ()
sum= Num_Buttons+Num_Editboxes
Reporter.ReportEvent 2, "Res","Total Buttons: "& Num_Buttons &"Total Edit boxes: "& Num_Editboxes
 

How to Get Oracle ERP Status bar Message in QTP/UFT?


Function ERP_Get_StatusMessage()
Set obj_ORAStatus=description.Create
If oraclestatusline(obj_ORAStatus).exist Then
ERP_Get_StatusMessage=OracleStatusline(obj_ORAStatus).getROProperty("message")
End If
Set obj_ORAStatus=nothing
End Function

Troubleshoot of Descriptive programming

This is another important concept in Descriptive Programming in UFT.

Case-1

Sometimes there may be two textboxes with the same name.

<input type="text" name="abc">
<input type="text" name="abc">

In that case we can code like: In this case, an index can be included in the collection to distinguish between these two objects


Set objDesc=Description.Create
objDesc("htmltag").value="input"
objDesc("name").value="abc"
objDesc("index").value="0"
Case-2

look at the code:

<input type="text" name="abc">
<input type="radio" name="abc">

In this case, even though the name is the same for two different objects, so regular coding will not help much. By using description we will be able to identify the objects properly.

Set objDesc=Description.Create
objDesc("htmltag").value="input"
objDesc("name").value="abc"
Browser("Browser").Page("Page").WebEdit(objDesc).set "xyz"
Browser("Browser").Page("Page").WebRadio(objDesc).click

Rule of thumb for description Programming

In the hierarchy of the page, if we are free to make any object as descriptive then the following child objects need to be descriptive in the same way. Otherwise, the mixture of the object repository will create confusion for UFT/QTP resulting in UFT or QTP will not be able to identify the object. This is another important concept in Descriptive Programming in UFT.


Browser("Browser").Page("Page").WebEdit(objDesc).set "xyz" // allowed
Browser("Browser").Page(pageDescription).WebEdit(objDesc).set "xyz" // allowed
Browser("Browser").Page(pageDescription).WebEdit("Test").set "xyz" // not allowed
Browser(browserDescription).Page(pageDescription).WebEdit("Test").set "xyz" // not allowed

When using programmatic descriptions from a specific point within a test hierarchy we must continue to use programmatic descriptions from that point onward within the same statement. If we specify a test object by its object repository name after other objects in the hierarchy have been described using programmatic descriptions, UFT/QTP can not identify the object.

This link will also help you to understand how to automate the network-related tasks.

Be careful when using dual monitor to open Object Repository

This is very interesting challenge while using UFT/QTP in dual monitors. The object repository is notorious to open in the second monitor and behind the active window.(Even if you are working on the primary monitor- Screen-1). Sometimes it is not visible too. This can also happen for laptop and second monitor, computer/laptop with a projector.
Solution: As per this website we need to use a keyboard shortcut to make it active in Screen-1(primary screen). The keyboard shortcut is ALT+spacebar then press M and press up/down/left/right key to make object repository appear in the primary monitor.

How to Use Repository Collection Object in UFT/QTP?

Repository collection object enables us to work with the shared object repository during execution or run time. This is another way to handle object repository but via code.

Repository collection provides us the below methods:

  1. Add()
  2. Find()
  3. MoveToPos()
  4. Remove()
  5. RemoveAll()

Repository collection provides us the below properties:

  1. Item
  2. Count
Details of Add() method

Add() method adds a shared object repository to the specified index during execution with the currently executing action. This method does not return anything.

Syntax:

RepositoriesCollection.Add(ObjectRepositoryPath,position)

Here ObjectRepositoryPath is a mandatory parameter and position is an optional parameter.

Example:

Dim my_repo_path
my_repo_path="C:\Test\xyz.tsr"
RepositoriesCollection.Add(my_repo_path)
Details of Find() method

Find() method returns the position of the specified object repository during execution or run time for the currently executing Action. This method returns a number specifying the position of the object repository.

Syntax:

RepositoriesCollection.Add(ObjectRepositoryPath)

Here ObjectRepositoryPath is a mandatory parameter.

Example:

Dim my_repo_path,pos
my_repo_path="C:\Test\xyz.tsr"
pos=RepositoriesCollection.Find(my_repo_path)
msgbox pos
Details of MoveToPos() method

MoveToPos() method can change the object repository position from the current index to a new user-specified index. This method does not return anything.

Syntax:

RepositoriesCollection.MoveToPos(ObjectRepositoryPath,currentpos,newpos)

Here ObjectRepositoryPath,currentpos, and newpos are mandatory parameters.

Example:

Dim my_repo_path,currentpos,newpos
my_repo_path="C:\Test\xyz.tsr"
currentpos=1
newpos=3
RepositoriesCollection.MoveToPos(my_repo_path,currentpos,newpos)
Details of Remove() method

Remove() method removes a particular object repository based on the index from the current Action. This method does not return anything.
Syntax:

RepositoriesCollection.Remove(index)

Example:

Dim my_repo_path,index
my_repo_path="C:\Test\xyz.tsr"
index=RepositoriesCollection.Find(my_repo_path)
RepositoriesCollection.Remove(index)
Details of RemoveAll() method

RemoveAll() method removes all object repositories available from currently executing Action. This method also does not return anything.
Syntax:

RepositoriesCollection.RemoveAll()

Example:

RepositoriesCollection.RemoveAll()

Details of Properties

Details of Count property

The Count property retrieves the number of object repositories from the currently executing Action. This property returns an integer that signifies the number of object repositories in the current action.

Syntax and Example:

Dim repo_count
repo_count=RepositoriesColleaction.Count
msgbox repo_count
Details of Item property

Item property retrieves the path information based on the index from the currently executing action.The output is the string representation of the path information of the object repository.
Syntax:

RepositoriesCollection.Item(Index)

Example:

Dim repo_path,Index
Index=1
repo_path=RepositoriesColleaction.Item(Index)
msgbox repo_path

Can you update object repository parameter at runtime?

We can get or set the values of repository parameters using repository object. Remember any change we will make using repository object is temporary and valid for current execution. They will stand void once the test finishes execution.

Setter method for object repository
Repository(ParameterName)=newValue
Getter method for object repository
value=Repository(ParameterName)
RepositoriesCollection.Add repositoryPath,position

repositoryPath can be an absolute path or relative path. If you do not wish to provide any position, the object repository will be added to the last of object repository collection.(index=-1).

UFT Object Identification process to Store in Object repository

Object Spy

Object spy is a tool provided by UFT or QTP to investigate an object. We can also see methods and properties.

How to open Object spy?

Navigate Tool–> Object spy to open and launch object spy.(A black color coat guy poses as spy or detective.). Once object spy is launched you can see a hand symbol or pointer appears on the screen.You can click control key of the keyboard to toggle to normal window.

Once you have determine the object to investigate, release control button and activate object spy and click on the object.The object spy will show the object hierarchy. You can check Test Object(TO) properties and methods along with Runtime Objects(RO). The selection is done by clicking on the radio.

The object spy pane has the following components

  1. Spy again.
  2. Highlight object to the application.
  3. Add object to the repository.
  4. Copy object property to clipboard.

The next pane shows the object Hierarchy after a successful spy.

The last section is the object properties and operations. If you select any object from the object hierarchy pane,you will get the properties and operation of the object.

Properties can be native or identification. Operations can be native or test object.Object spy is also available from the object repository window.

UFT Mandatory Property

Logical name

Logical name is an unique identifier provided by UFT/QTP to identify the component uniquely from other objects in the application. This name is used by UFT/QTP to map between object and its properties.

You can not remove association between an action and its local repository. But you can edit the logical name if you want to make it clear for you and your team.

UFT Ordinal Identifier:

If there are more than one objects with same class name,properties,UFT/QTP will not be able to identify uniquely with mandatory or assistive properties. In that case UFT/QTP activates ordinal identifiers. Ordinal identifiers are kind of numerical values that are assigned to objects to identify the object uniquely.

The ordinal identifiers can be

  1. Index
  2. Location
  3. CreationTime
Index:

Index is assigned from top to bottom or below.

Location:

If location property is taken by UFT, the index is assigned left to right and top to bottom.

CreationTime:

CreationTime holds good for web application. If we open two or more web  browsers (mainly in Internet Explorer), UFT/QTP will not be able to identify the web browsers uniquely. In that case it determines by CreationTime. The first opened browser is identified by CreationTime:=0 and the second one will be CreationTime:=1 and so on.

In order to work with the browser we need to code like:

Browser("CreationTime:=index").activate

Where index starts from 0 to no of open browser count-1.

Visual Identifier

The relative position of an object gives more reliable object identification.

How to use property which is dynamically changing?

If the value of a particular property for an object changes,you can activate regular expression(click on the checkbox). You can provide ‘.’,’*’,'[]’ ect to define an object property.

Alternatively you can select datatable or environment or random number. We need to activate radio button ‘parameter’ and create necessary settings.

Automatic Object Model and Object Repository

In UFT/QTP , Automatic object model enables you to manipulate UFT/QTP shared object repositories and their contents from outside of the UFT/QTP.

The Automatic object model enables you to use a scripting language to access UFT/QTP shared object repositories via automation.

UFT/QTP object model can be used to automate UFT/QTP operations. You can use the objects and methods of the object repository automation. Automation object model helps to write programs that manipulate shared object repository, instead of performing these operation manually using object repository manager.

After you have received the object,you can manipulate it using the methods and properties available for the test object class. You can use GetToProperty or SetToPorperty method to fetch and modify object’s property.

ObjectRepositoryUtil Object the fuel of Automatic Object Model

ObjectRepositoryUtil object helps us to work on or manipulate shared or local object repositories from outside of the UFT/QTP via automatic Object Model.

ObjectRepositoryUtil object provides the below methods

  • AddObject()
  • Convert()
  • CopyObject()
  • ExportToXML()
  • GetAllObjects()
  • GetAllObjectsBy()
  • GetChildren()
  • GetChildrenByClass()
  • GetLogicalName()
  • GetObjectByParent()
  • ImportFromXML()
  • Load()
  • RemoveObject()
  • RenameObject()
  • UpdateObject()
  • ToCollectionObject()
  • Save()

Details of the methods:

AddObject()

AddObject() method adds a specified object to the local or shared object repository under the specified parent object. AddObject() method further helps to add an object that is being copied from another repository. AddObject() method also supports modifying object properties (description) by using SetToProperty before adding the new object to the repository.

Syntax:

Object.AddObject(newObject,Parent,Name)

newObject is the new object that needs to be added to the repository. It is a mandatory argument.Parent is the object under which the new object will be placed. It is also a mandatory argument. Name is an optional argument.

Convert

Convert() method converts older like QTP 8.2 or former object repository to the current working format. We can directly use convert() method to convert older object repository to newer version without using Load() method.

Syntax:

Object.Convert(oldFilePath,newFilePath)
CopyObject()

CopyObject() method creates a copy of the specified object in the same repository. It just duplicates an object during runtime. To copy from one object repository to another object repository , we need to copy object then load the second object repository and then call the AddObject() method.

Syntax:

Object.CopyObject(ExistingObject)
ExportToXML()

ExportToXML() method exports the specified object repository to the XML format.

Note

  • Plain test objects without the checkpoints or output values are exported to XML.
  • Local object repository can not be exported to XML. Only shared object repository can be exported.
  • The latest version of UFT (version 9.0 onwards) supports the export to XML.
  • Older repositories need to be converted first using Convert() function to the latest in order to export to XML.

Syntax:

Object.ExportToXML(sourceFilePath,XMLFilePath)
GetAllObjects()

GetAllObjects() method returns all objects from a specified parent object from a specified object repository. GetAllObjects() methods returns a collection of objects. We need to use a For Each…Next loop to loop through each object from the collection to get all object related information.

Syntax:

myCollection=Object.GetAllObjects(Parent)
GetAllObjectsBy()

GetAllObjectsBy() method accepts a specific class, provides another filter option available to get all objects of that specified class for the specified parent object. GetAllObjectsBy() method returns a collection of object information about the objects.We need to use For Each… Loop through each object from the collection to get the specific objects related information.

Synatx:

coll=Object.GetAllObjectsByClass(class,parent)
GetChildren()

GetChildren() method returns all direct children of the specified parent. GetChildren() returns a collection of object information about the children objects. We need to use For Each… Next loop to loop through each children object from the collection to get the specific objects related information.

Syntax:

coll=Object.GetChildren(parent)
GetChildrenByClass()

GetChildrenByClass() method returns a collection of children objects from a parent object of a specified class.As this method returns a collection of object information about the children objects. We need to use For Each… Next loop to loop through each children object from the collection to get the specific children objects related information.
Syntax:

coll=Object.GetChildrenByClass(Class parent)
GetLogicalName()

GetLogicalName() method returns a string representing the logical name of the object.
Syntax:

obj_name=Object.GetLogicalName(targetObject)
GetObject()

GetObject() method returns the objects available from an object repository based on the path. This is useful when we do not have access to the parent object of the target object.As this method returns a collection of object information about the children objects. We need to use For Each… Next loop to loop through each children object from the collection to get the specific objects related information.
Syntax:

coll=Object.GetObject(ObjectRepositoryPath)
GetObjectByParent()

GetObjectByParent() method is useful when you have access to the parent object. It returns a collection of objects based on the parent information.As this method returns a collection of object information about the children objects. We need to use For Each… Next loop to loop through each children object from the collection to get the specific objects related information.
Syntax:

coll=Object.GetObjectByParent(parent,object)
ImportFromXML()

ImportFromXML() method imports the specified XML file to share object repository. This method can not be applied to import local object repository.The XML will have only test objects and its descriptions. No checkpoint information or output values can be imported by this method.
Syntax:

Object.ImportFromXML(SourceXMLFilePath,TargetXMLFilePath)
Load()

Load() method loads an object repository to the current test action. We can load multiple object repositories by creating required number of RepositoryUtil objects.
Syntax:

Object.Load(ObjectRepositoryFilepath along with name)
RemoveObject()

RemoveObject() method removes a specified object from object repository.
Syntax:

Object.RemoveObject(parent,object)
RenameObject()

RenameObject() method renames a specified object located in the object repository.
Syntax:

Object.RenameObject(Object,newName)
Save()

Save() method saves all changes made to the object repository during execution.
Syntax:

Object.Save
UpdateObject()

UpdateObject() method updates the object repository if any changes has been made during script execution.
Syntax:

Object.UpdateObject(targetObject)

Introduction to File System Object(FSO)

FSO provides us the ability to work with files and folders. FSO will also covers on how to work with folders.

Data Types in UFT

UFT supports VBScript Data types.

Variables in UFT

UFT supports VBScript variable concept.

Creating Tests (Using Object Repository or Descriptive Programming)

Automation process Using UFT

The automation process is the basic building block of UFT test cases. The Automation testing via UFt consists of the following processes:

  1. Prepare for recording.
  2. Actual recording
  3. Enhancing test script.
  4. Debugging
  5. Analyze the result
  6. Reporting

Recording in UFT

The recording is the fundamental process of building the test script.

Preparing for recording:

Before we start hitting the recording button, we need to make sure the application is stable and the object is constantly visible for recording to happen.

Before you start recording it is always better to close all other applications or web pages.

In Record and Run settings, we can define if we want some default application to open during recording similarly for web, in web tab we can define if some predefined webpage we want to open.

After the recording, you can use the stop recording button to stop recording.

Recording in UFT

As and when, we navigate through the application or web pages using UFT recording, UFT will mimic the same steps in keyword view and expert view. In the keyword view, the steps will come as rows and columns and in expert view, it will come as plain code.UFT supports 3 recording mode to combat different scenarios.

Different Recording modes of UFT:

Recording a test is to keep a track of the user’s behaviors and actions on the application. Recording helps UFT to translate these actions into the test script. The recording also acts as a quick check if the application under test is supported by the tool for carry out testing.

UFT/QTP supports record and playback options. Recording modes of UFT enables us to understand object learning better during the recording phase. Different types of recording modes(Standard recording mode, analog recording mode in uft, Low-level recording mode in uft) enables us to automate the different types of scenarios. It is very important to understand about the recording options available in UFT/QTP.

UFT Recording modes
UFT Recording modes

we have four recording options.

  • Standard recording mode  default recording mode based on object’s properties.
  • Analog recording mode- based on keyboard and mouse operation
  • Low-level recording mode- coordinate based but not based on object properties
  • Insight Recording mode-  based on operations on the UAT and its appearance but does not depends on object properties.

This-how many types of recording modes in uft? is a very popular question in the interview as well

Standard Recording Mode

This is the default mode in UFT/QTP which can record all operations. UFT/QTP’s normal recording mode records the objects in our application and the operations performed on them.

This mode is the default and takes full advantage of UFT/QTP’s test object model, recognizing the objects in our application regardless of their location on the screen.

Navigation for standard recording:

Automation>Record
or
Select Record option on automation toolbar
or
Use shortcut key (F3)

During recording UFT generates VbScript statements in Test Pane, Simultaneously it stores objects information into object repository.

Steps for Normal recording:

We need to perform the following steps for preparing a Test (through Recording):

  • Put AUT in base state
  • Select Record Option
  • It shows Record and Run Settings, Select type of Environment (Windows or Web)
  •  Select Record Option (It shows two Options)
    Record and Run Test on any open window-based applications
    Record and Run only on If we select the first option it records on any opened application on Desktop. If we select the Second option, it asks for the path of the AUT, After Providing the path it records only on that particular application.)
  • Click OK
  • Perform actions on AUT
  • Stop recording.
  •  Save the Test

While answering different types of recording modes in uft , just remember, low level and analog recordings are not very popular among the test gurus so they don’t like it much. Focus on the normal mode. It is very important.

Here is the way to record in normal mode:

  • Click the Record button or choose Automation > Record. If we are recording for the first time in a test and have not yet set our recording preferences (by opening the dialog box manually), the Record and Run Settings dialog box opens. It is divided by environment into several tabbed pages.
  • To choose an environment, click a tab.


  • Set the required options, as described in the following sections.
  • To apply our changes and keep the Record and Run Settings dialog box open, click Apply.
  • When we have finished the operation, click OK to save our changes and start recording. Guidelines for Modifying Record and Run Settings After we set the record and run settings for a test, the Record and Run settings dialogbox will not open the next time we record operations in that test. If needed, we open the Record and Run Settings dialog box by choosing Automation > Record and Run Settings.

We should set or modify our record and run preferences in the following scenarios:

  • We have already recorded one or more steps in the test and we want to modify the settings before we continue recording.
  • We want to run the test on a different application or browser than the one we previously set in the Record and Run Settings dialog box.

If we change the record and run settings for additional recording sessions, we need to confirm that we return the settings to match the needs of the first step in our test before we run it.

How to record the web ?

Record and run test on any open browser Instruct UFT/QTP to record on any open Microsoft Internet Explorer browser and run on any open supported Web browser (refer to the UFT/QTP Professional Readme for information on supported browsers).

Note: We must open the Web browser after we open UFT/QTP and select this option.

Tip: we can instruct UFT/QTP to ignore selected browsers that are open during the record and run session. Open the following address when a record or run session begins Instructs UFT/QTP to open a new browser session to record and run the test using the specified URL address.

When recording a test, the address is opened in a Microsoft Internet Explorer browser. When running a test, the address is opened in the browser type specified in the Open the following browser when a run session begins box.

Note: If we define a value for the URL_ENV environment variable, that value overrides the value specified here during a run session. Open the following browser when a run session begins Instructs UFT/QTP to open the specified browser type when running a test:

  • Microsoft Internet Explorer
  • Netscape 8.x
  • Firefox 1.5

Notes: Only those browsers currently installed on our computer are available in the list. If we define a value for the BROWSER_ENV environment variable, that value overrides the value specified here during a run session. Do not record and run on browsers that are already open Instructs UFT/QTP not to record or run tests on any browsers that are already open prior to the start of the record or run session (and prior to opening UFT/QTP).

Selecting this option also prevents us from viewing the properties of these browsers using the Object Spy. Close the browser when the test closes Instructs UFT/QTP to close the browser window specified in the Address box when the test closes.

How to record Window-based Applications?

Option Description Record and run test on any open Windows-based application Instruct UFT/QTP to record and run on any open Windows-based application.

Note: We need to make sure that all the applications on which we want to record are currently closed. UFT/QTP can record on the applications that we open manually only after we select this option and click OK.

Instances of these applications that are already open when the Record and Run Settings dialog box opens may be ignored or may not be recorded correctly. Record and run only on Instructs UFT/QTP to restrict its record and run operations to one or more of the following options:

Applications opened by UFT/QTP:

This option records and runs only on applications invoked by UFT/QTP (as child processes of UFT/QTP). For example, applications opened during a record or run session using a SystemUtil.Run statement, or using a statement such as

Set shell = createobject("wscript.shell"); 
shell.run "notepad".

Applications opened via the Desktop (by the Windows shell):

This option records and runs only on applications that are opened via the Windows Desktop. For example, applications opened from the Windows Start menu, by double-clicking executable files in the Windows Explorer, by double-clicking a short cut on the Windows Desktop, or by clicking icons on the Quick Launch bar.

Applications specified below:

This option records and runs only on applications listed in the Application details area. This is the recommended option to use. When working with standard Windows applications only, we can manually add steps to our test and then run them, even if we select this option and leave the Application details area blank (or if the list does not contain the application for which we want to add a step).

Note: Make sure that all the applications listed in the Application details area are currently closed. UFT/QTP can record only on the instances of the specified applications that are opened after we select this option and click OK.

Instances of these applications that are already open when the Record and Run Settings dialog box opens may be ignored or may not be recorded correctly. Application details List the details of the applications on which to record and run the test. For more information on the details displayed.

If we define values for one or more environment variables, those values override the values in the Windows Applications tab during a test run. By these above methods, we can get the script but in the object repository, we might get extra unnecessary objects. So to avoid this a little advanced approach will be to add those required objects to OR[Object repository] and then perform normal recording. Shortcut Ctrl+R or by navigating to Resources to the Object repository.

Disadvantage:

It records User Mouse and Keyboard operations on AUT with respect to objects, but unable to record continuous mouse operations like Digital Signatures, graphs, paints, etc. When working with specific types of objects or operations, however, we may want to choose from the following, alternative recording modes:

Analog Recording Mode:

This is the second Recording modes of UFT. Here UFT can identify the object but can not record. For example, UFT can identify the paint/drawing bar normal mode but can not draw the picture or can not draw a signature by normal mode. To solve such a problem we will choose the analog recording mode.

UFT will identify the object and the analog operation over it. It will record the keyboard and mouse movement on the recognized window. Similarly, when testing signature we use Analog Recording Mode. Analog Recording enables us to record the exact mouse and keyboard operations we perform in relation to either the screen or the application window.

In this recording mode, UFT/QTP records and tracks every movement of the mouse as we drag the mouse around a screen or window. We can use this mode for recording continuous mouse operations. however it does not generate steps for each operation, generates total user actions in a Track File. The Track file is not editable.

There are two modes of recording:

  1. Relative to a specific window
  2. Relative to screen

while answering different types of recording modes in uft, we may touch this portion, Relative to a specific window is more important over Relative to screen

Relative to the window:

Activate this option if and only if operations performed on UAT located within one window. During analog recording mode in uft, UFT tries to identify the window location and can perform operations(record the analog step) even if it is located in a different locations. Interestingly UFT does not record any keyboard operation or mouse movement outside this window. Active Screen image of the final state of the window is captured.

Relative to Screen:

This is a very rare scenario where we need to perform some analog recordings with respect to the screen. This is applicable during run time that is execution time also. It can also be possible if the AUT is having multiple windows opened. No active screenshot is taken/captured during this type of recording

Best to use while Automating:

1. Paint operation
2. Drag and drop

 Navigation:

1. Keep tool under recording mode
2. Automation >Analog Recording OR Use Short cut Key (Shift + ALT+F3)

Steps for preparing a TEST (through Analog Recording):

In order to perform the analog recording, we have to do the followings

  • Launch AUT (or we can launch AUT through UFT)
  • Select Record option
  •  Automation>Analog Recording
  •  Analog Recording Settings Dialog box opens (In this Dialog box two options available.

The record relative to the screen
The record is relative to the following window If we select first option UFT records User operations with respect to Desktop co-ordinates. If we select the second option, we have to show the window (AUT), after showing the Window it records with respect to that window co-ordinates.)

  • Select any one option in the dialog box and click Start Analog record.
  • It records User actions
  •  Stop Recording This mode is useful for recording operations that cannot be recorded at the level of an object, for example, recording a signature produced by dragging the mouse. Note: we cannot edit Analog Recording steps from within UFT/QTP. To execute this UFT invokes RunAnalog command like-
Desktop.RunAnalog "Track1"
' This is for Relative to the scren but for relative to a window the code will be--
Window({name of the window}).RunAnalog "Track2"

Both this two recoding mode eats up huge disk space. So please do not use these if not required. Mixing of the normal analog mode of recording is possible and we can switch to these modes if required. In general, avoid analog recording mode in uft.

Low-Level recording:

This is the third Recording modes of UFT. UFT can not identify the object under test. Hence it can not proceed with recording. As UFT can not identify or recognize the application under test, Analog Recording Mode can not be operated. So if we need to test such an application, we need to activate Low-Level recording.

By enabling this mode of recording, UFT will identify objects and by default class window or win Object and will record all keyboard and mouse operation. Low-Level recording enables we to record on any object in our application, whether or not UFT/QTP recognizes the specific object or the specific operation. This mode records at the object level and records all run-time objects as Window or WinObject test objects.

Use Low Level Recording for recording in an environment or on an object not recognized by UFT/QTP. we can also use Low-Level Recording if the exact coordinates of the object are important for our test. In this level of recording, UFT identifies coordinates mostly to record and run.

While different types of recording modes in uft, we should touch this point but keep it short and be honest if we have not used this feature.

Note: Steps recorded using Low-Level Recording mode may not run correctly on all objects. It records some operations on Non-supported environments apart from Normal operations. This mode records at the object level and records all run-time objects as a window or winobject Test objects. Use Low-Level Recording for recording in an environment not recognized by UFT.

Mouse movements are not captured during low-level recording.

 Navigation:

To record in the low level we have to perform the following steps:

  • Keep tool under recording mode
  • Automation > Low-Level Recording

Steps for preparing a TEST (through Low-Level Recording):

  • Launch AUT (or we can launch AUT through UFT)
  • Select Record option
  • Automation> Low-Level Recording
  • Perform options on AUT
  • Stop Recording
  • Save the Test So similarly between analog and low-level recording, in both cases, UFT uses keyboard, mouse and work on co-ordinates. But the difference is in Analog mode UFT can identify the object in UAT but in Low-level recording, it can not.

One more important aspect of the low-level recording is it majorly depends on the co-ordinates. So in normal mode if the coordinates change for an object,still UFT will identify the object and performs operations.

But in such a case where coordinates like the location of the object is very important, we can use the low-level recording to check the location of the object. Mostly It supports Click,DbClick,Drag,Drop,Type,Activate,Minimize,Restore etc.

different types of recording modes in uft also bring the step details into the table. just follow this guideline once. we will mostly not forget.

Steps to follow before we start recording:

1. Before we record a test, confirm that our application and Quick Test are compatible with each other.
2. Start QTP Check the required Addin in Add-ins manager. Else add those. Like for java application we need to have JAVA add-in. While UFT/QTP loads our selected add-ins, the UFT/QTP splash screen is displayed. This may take a few seconds. confirm that the Web Add-in is selected, and clear all other add-ins. Click OK to close the Add-in Manager.
3. Make sure the application is ready.i.e.Make sure our application displays elements on which we want to record, such as a toolbar or a special window pane, for example, and that our application options are set as we expect for the purposes of our test.
4. we should also view the settings in the Test Settings dialog box (File > Settings) and the Options dialog box (Tools > Options) to ensure that Quick Test will record and store information correctly.
5. if we are using Internet Explorer as our browser, the AutoComplete option is cleared for user names and passwords.
6. Please close all the other browsers.
7. If the Welcome window opens, click Blank Test. Otherwise, choose File > New, or click the New button.

Is it possible to switch between recording modes during test creation?

Yes, It is absolutely legal to switch between recording modes during test creation. However, switching to Analog mode is only possible during recording but not during editing.

Remember Analog and Low-level recording mode are very expensive in terms of system resource like- memory. Hence we need to use them occasionally.

last but not the least, different types of recording modes in UFTtopic also put us in a situation where test guru may want to know how will tackle dynamic events?

Remember this recording mode does not help to capture the dynamic behavior of the website. Read here to get details on how to capture the dynamic behavior of a page.

Insight Recording in UFT

As I said earlier, Insight recording ios based on the appearance of the object. Here are the two best articles already present.

If you enjoyed this post, please share it on social media ?”What am I missing here? Let me know in the comments and I’ll add it in!”

Understand the recording

Once you have completed the recording in UFT the keyword view will be like below:

ItemOperationValueDocumentation
Action1Name of the action
ParentWindowThe main window which UFT will refer for further recording
Child ObjectSet/SetSecure/Click etcsomevaluebased on the object the operations are defined in this format.
The value is the value that the object will take during recording.

Enhancing Tests

(Inserting Checkpoints, Output Values, Transaction points, Flow Control Statements, Synchronization, Parameterization—etc )In this phase, we need to create some validation points.

Enhance test script:

In this phase, we will insert checkpoints, attach the tests with different data, update the script with environment variables. We will also make the recorded script dynamic by using the conditions and loops.

Get Values or SetValues and checkpoints:

I not a big fan of Checkpoints available in UFT or QTP as they are unreliable at times. But inserting checkpoints we can search for specific values from the page, object or text String. Checkpoints determine if the application is working properly.

How to work with output values?

Output values in UFT allow us to test the values of an object or allow us to pipe the output of one script or component to others.

It is a step in which one or more values are captured during test execution and are stored in output values. The values can be retrieved later and can be used as input at a different point in the run session or we can use as input for another test.It is stored in run time data table; it is located in QTP/UFT result window.

The values of properties of any object can be exported via output values.Output values techniques also allow us to fetch data from the below written sources:

  • Text strings
  • XML document
  • Databases
  • Table cells

Note: Output values are valid only during run session. Once the execution is over, the values get resetted.

It is always good to learn Checkpoint in UFT in order to understand the Output values better.

Where the output values get saved?

The output values can be saved the following areas:

  • Action or Component(if BPT is used).
  • The runtime datatable.
  • An environment variable.

We can define the output values and it location while configuring the output values.

How to pass parameter to action or component?

we will be able to pass parameters to an action or component parameter. This is helpful to supply values later during the run session. The values can also be passed to external application during script execution which will call the test or component.

It is mainly dependent on two parameters:

  • Type- Shows the type of parameter like- String
  • Description- Shows the description defined for the parameter.

How to pass output data/ parameters to Data table?

We will be able to pass the data and store the output values in datatable. In the datatable we can store inside the followings:

  • Global sheet
  • Action sheet
  • All different actions in the current test.

The following options are important while we place output values to data table:

  • Name- The column name in which the value will be saved.
  • Location- In which sheet the data will be stored?(like -global or action sheet)

How to pass output values to an environment variable?

We will be able to store the output values to an Environment variable. We can select the Environment as the output type in the output options dialog box(dropdown). The Environment variable will be off user-defined Environment variable. In that Environment variable we can store the output value.

The two important aspect of Environment variables are :

  • Name- Name of the user defined environment variable in which we will store the output value.
  • Type- It is read only and cannot be edited or altered. The value will be User defined-Internal.

The out of the box UFT addins and their support for output values

Output ValueWebWindowsVBActiveX
StandardYYYY
Page(Standard)YNANANA
Table(Standard)YNANAY
TextY(Page frame and view link)YYY
TextAreaNAYYY
DatabaseYYYY
XML from ApplicationYNANANA
XML from resourceYYYY

Y stands for supported and NA stands for not applicable/not supported

Types of Output Values:

  1. Standard output value
  2. Text output value
  3. Text area output value
  4. Database output value
  5. XML output value (From Application)
  6. XML output value (From Resource)
Standard output value:

We can use standard output values to output the properties values of most objects. Like- number of links present on a web page.We can also create standard output values to output text string by providing the text property of the object as an output value.

Navigation for Creating Standard output values:
  • Open a new test
  • Keep tool under Recording mode
  • Click on Insert menu >output value> standard output value [at this point UFT will be minimized and a hand symbol will come]
  • show the object > click ok [It will open the Object selection-output value properties window]
  • The output values properties window will open.
  • select property in order to read the property
  • Modify the column name (if required) > click ok [This will open Output options window]
  • Select the output type in list box.
  • Enter the column name where you want to store the value.Like Datatable
  • click ok
  • Stop recording.

The code will look like:

Window("WindowName").WinButton("ButtonName").Output CheckPoint("PropertyName")
Text output value

We can use Text output values to output text strings displayed in an application, web page,screen. When creating a text output value we can output a part of the objects text and we can also specify text before and text after options.

Navigation to create Text output value:

  • Start a new test
  • Keep tool under recording mode
  • Insert menu> output value > text output value[UFT will be minimized and a hand symbol will appear on the screen]
  • Select the object. It will open the Object selection-output value properties window.
  • Click  on ok. It will open the Output values properties window.
  • show the text
  • select one of the option(output text/text before/text after)
  • Click modify if you want to change the column name. It will open Output Options window.
  • select one of the option(output text/text before/text after)
  • Select output type in the list box like datatable or environment variable. Incase we select the datatable we need to provide column name to store the value in the runtime.Similarly if we select the environment variable we need to specify the Environment variable name.
  • > click ok > click ok.> check in runtime table after running it.

The code will look like:

Window("WindowName").WinButton("ButtonName").Output CheckPoint("PropertyName")

Text Area output value:

We can use text area output values to output text strings displayed within a defined area of the screen. Apart from these Text Area output value can fetch text present in the bitmap or strings from an object.

Navigation for inserting TextArea Output values:
  • Open a new Test.
  • Keep tool under recording mode
  • Insert menu >output value > text area output value[UFT will be minimized and a hand symbol will appear on the screen]
  • Mark the text area
  • Select the object. It will open the Object selection-output value properties window.
  • Click on OK. It will open Output Values Properties window.
  • Click modify the column name if necessary. Options window opens.
  • Select Datatable if you want to store data in the datatable. In that case specify the column name and sheet name. If you are selecting environment variable provide the environment variable name
  • > click ok > again click ok > check in run time table after running it.

The code will look like:

Window("WindowName").WinButton("ButtonName").Output CheckPoint("PropertyName")
Database output value:

We can use Database output values to output the value of the contents of database cells. The data is dependent on the query(a result set) to the database. The output value can be created from the entire content of the result set or some parts of it.

Navigation to insert Database output value:
  • Open a new Test
  • Insert menu-> output value-> Database output value
  • choose specify SQL statements manually ->click next ->click create
  • Select Machine Data source -> Select Driver (Or DNS)
  • Enter SQL statement or query
  • Click on Finish
  • Select data cells to fetch data
  • Click on Modify if you need to change
  • Specify the parameters name
  • click ok > Run and it will capture and see the results in run time table.
XML output value (from application):

we can use XML output values to output the values of XML elements (attributes, variables, elements) in XML documents.

Navigation XML output value (from application):
  • Open a new Test
  • Keep tool under recording mode with web environment
  • Insert menu > output value > XML output value from application
  • Show the XML document > select elements > click ok >stop recording.
XML output Value (From Resource):

We can use XML output values to output the values of XML elements (attributes, variables, elements) in XML documents.

Navigation XML output Value (From Resource):
  • Start a new Test
  • Insert menu >output value> XML output value from resource
  • Browse path of the XML file
  • Select the variable attributes
  • Click on Modify to change the column name
  • click ok

This article also provides answer for the following questions:

  • What are the output parameter types in output values?
  • What are the difference between Text output values and Text Area Output values?
  • Where do we store output values?
  • Why we will use Output values?

The very next topic is Variable:

Read here for more details on Variables.

Environment Variable in UFT:

Read about Environment variables here

Loop and conditions in UFT

By loop and conditions, we can upgrade our script and put intelligence.

Datatable related Operations:

How To Work With Datatable In QTP or UFT

This Post Also talks about How To Work With Datatable In UFT. If we are working on QTP/UFT for quite a few time the immediate question comes like how to parametrize my test?

How to check a scenario with multiple sets of data. Unlike other automation tools, QTP/UFT also provides a data-driven or data-oriented concept called data-table to parametrize our tests.

So data book or databank is used to pass the inputs to the script and also to capture output or live data from the script during run time.so basically using of data table is required when we want to run a test multiple time with multiple data.

The basic example could be to test login module. In login we will provide several user id and password and test if it is working fine or not.

Four Commonly Used Methods on ComboBox in QTP/UFT

In an application today Combo box or select box or drop down is an essential part. Here developers provide choices that should be selected by user. Advantages of combobox or select box or dropdown is that it is single linear in view and restricts users to provide multi form of same data.
Very popular example could be country or state drop down. Say in a registration form ,User from India needs to select Country as India.But if this would have been a textbox, user might put Country -India  or INDIA or india. This will go to server as String.From technological point of view these are three different Strings!!!.
So by providing India on dropdown developers restrict user to select a single,defined String called India.

Commonly user methods on Combobox or Dropdown or select in QTP are-

  • Count of Items in Combobox or Dropdown or select
  • Fetch specific item from Combobox or Dropdown or select
  • Complete List of items from combobox or Dropdown or select
  • Select one from Combobox or Dropdown or select

Let us do one by one-
How to get Count of Items from Combobox or Dropdown or select
For getting count of Items from a Combobox or Dropdown or Select we will use getItemCount method.
Syntax-Variable_Name= <Hierarchy of Object >.Combobox(“Combobox_name”).GetItemsCount

dim x
x=Window("abc").WinComboBox("xyz").GetItemCount
//abc and xyz can be fetched from Object spy
//for descriptive programming
dim x
x=Window("Title:=abc").WinComboBox("name:=xyz").GetItemCount

How to get specific item from Combobox or Dropdown or select
For this case , the command we will be using is GetItem(Position).position starts from 0. It is nothing but Index value.
Syntax-Variable_Name=<Hierarchy of Object >.Combobox(“Combobox_name”).GetItem(2)

dim x
x=Window("abc").WinComboBox("xyz").GetItem(2)
//abc and xyz can be fetched from Object spy
//for descriptive programming
dim x
x=Window("Title:=abc").WinComboBox("name:=xyz").GetItem(2)

How to get complete list of Items from Combobox or Dropdown or select
For this we will be using GetContent method
Syntax-Variable_Name=<Hierarchy of Object >Combobox(“Combobox_name”).GetContent

dim x
x=Window("abc").WinComboBox("xyz").GetIContent
//abc and xyz can be fetched from Object spy
//for descriptive programming
dim x
x=Window("Title:=abc").WinComboBox("name:=xyz").GetIContent

How to select specific item from Combobox or Dropdown or select
Select is the command to set a value in the combo box
Syntax-
Variable_Name=<Hierarchy of Object >.Combobox(“Combobox_name”).Select(Value_To_Select)
or
Syntax-
Variable_Name=<Hierarchy of Object>.Combobox(“Combobox_name”).Select(Index_Value)

dim x
x=Window("abc").WinComboBox("xyz").Select("pqr")
//abc and xyz can be fetched from Object spy
//for descriptive programming
dim x
x=Window("Title:=abc").WinComboBox("name:=xyz").Select(2)

How To Create Parameterization in QTP or UFT?

When recording a Test step, it is more about static in nature as the data are hardcoded in the script. Parametrization is the very next step while making test dynamic in nature. Now let us understand what is a parameter? A parameter is a variable that is assigned a value from different sources or generators. You can say a variable to store temp data.

Through Passing parameters, we can pass multiple values.We use parameterization in Data Driven Testing. Parameterization is an integral part of advance scripting or frameworks specially the data driven testing.

Parameterization helps running the same script with multiple data set over and over.

Which phase we can provide data to Script

How to get data from different source:

  • Through Loop Statements
  • Dynamic Test Data Submission,user input during execution
  • Through Data Table
  • Fetching Test Data directly from External files (Flat files & Spreadsheets)
  • Fetching Test Data directly from Databases (MS Acess, oracle etc).
  • Getting Test Data from front end objects.
Phases of test where you can give some data

Parametrization Through Loop Statements:

We can use loop statements for passing sequential numbers & Logical Numbers.

For order_no=1 to 10 step 1 ' for one increment step keyword is not mandatory
Window("Flight Reservation").Activate
//activate the Flight reservation window
Window("Flight Reservation").WinButton("Button").Click
//Click on the reservation button
Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON"
//Setting the order check box as true
Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set order_no
//Providing looping value
Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click
Next

Even we can create several other users like Users_1 to user_n,Order_1 to order_n,Item_1 to Item_n etc. But with this approach, we can not generate  and operate strings.

Through Data Table:
QTP/UFT adds one data table (Spreadsheet) for every test, we can use Data Table for Data Driven Testing.
It has four types of usage

  • Entering test data directly into the data table and use them as per need
  • Importing test data from external Flat files(.txt,.csv)
  • Importing test data from external Spreadsheets(.xls,.xlsx)
  • Importing test data from Databases.(Oracle,MySQL)

Via Datatable:
We will use the datatable syntax for getting values:

variable xyz=datatable("column name", Sheet id)

Let’s see how it works:

Agent = Datatable("Agent",1)
pwd=Datatable ("Password",1)
invokeapplication "E:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"
Dialog("Login").Activate
Dialog("Login").WinEdit("Agent Name:").Set Agent
Dialog("Login").WinEdit("Agent Name:").Type micTab
Dialog("Login").WinEdit("Password:").SetSecure pwd
Dialog("Login").WinButton("OK").Click
Window("Flight Reservation").Close

if you are using action based framework , the method can be called but data will come from action datatable.
Dynamic User input:
This is such a type of data that is a bit dynamic but needs manual intervention for making it dynamic. So with the help of the input box, we get data from the user and feed it into the script.


Dim myInputVariable
myInputVariable=InputBox("Please Enter the Name")
msgbox(myInputVariable)

For every test by default there would be 2 sheets
1.Global
2.Action

just by clicking the different sheets we can acess these tables.

Global :-

Global sheet is neutral for all actions. If we want some data to be available all actions in our test, we will be using Global data.This is a default data table. So if you create your test and create your test data in excel, you can rename the test data excel file as global and paste it in the data table folder, those values will populate.

  •  Mostly we will be using MS-Excel for QTP. There are two methods to invoke one excel file to your test.
    1.1. Save your test to a specific folder.
    1.1.1. Open that folder via window explorer.
    1.1.2. Find Default.xls
    1.1.3 Rename it as Default-old.xls
    1.1.4 Now rename your datasheet as “Default.xls”
    1.1.5 Paste it here.
    1.1.6. Reopen your script viz test.

you can find the excel is populated in the datatable area with exact sheetnames given in that excel.

2. Otherwise you can dynamically add excel file through code.
I would say this is very good method. Every time you invoke a excel file that will load into your primary memory . So it is going to consume the primary memory. It is better to load files whenever required.

Action:

If we are using different actions,We can store data in the action’s tab but scope is for current action only.
if your underlying data source is Excel , there might be some formula inbuilt in it. QTP has an ability to learn those formula and value from it.  So based on our scope for testing we might pass different datasource.

Datatables are of 2 types in Quick Test

  • Design Time Datatable:-The table that is associated with the test before and after the test execution. During execution this got transformed to runtime data
  • RunTime Datatable:- The table that is associated with the test during the test execution and will be present in the “Results” after test execution.A live dataset.

by default datatable will be stored by QTP under testname–>Datatable folder. If we want to use some other source , we need to code it accordingly.Where it is applicable?
say I am testing two different versions of the same application like-Webversion and Windows version. So the application data might be same but we need to use it from two different location.
Again say I am testing localization testing  of an application, So based on the location I need to pick some other datatable.Such cases this case comes handy.

Supported versions of data souce:

Excel-95
Excel-97
Excel-2000
Text files(.txt,.csv)
ASCII format
Even the zip files–
File–>import Test from Zip

Datatable object methods:

AddSheet:-Adds the specified sheet to the run-time Data Table and it returns the sheet so that we can add properties to the sheet in the same statement.

Syntax:

datatable.addsheet("sheetname")

Example

datatable.AddSheet "sheet1"

How to set parameter/properties to it?
Syntax:


datatable.addsheet("sheetname").Addparameter(Col_Value,Value)

Example


datatable.GetSheet("Sheet1").AddParameter "Fly From",""

Next method will be deletesheet
This method will delete a specific sheet from the data table during run time.
Syntax:

datatable.DeleteSheet sheetName

Example

datatable.DeleteSheet"sheet1"

Export :-Saves the copy of the run-time datable in the specified location.
Syntax:-


datatable.Export ("location along with Excel name")

Eg:-


datatable.Export "d:animesh.xls"

Note :- if the file is not created /present QTP will create the file at runtime and exports the specified sheet.

ExportSheet :- exports the specific sheet in the run-time datatable to An Excel file .
Syntax :-


DataTable.ExportSheet "location along filename", "sourcesheet"

Three things to know:
1. if the file is not present or created QTP will create the file at runtime and exports the specified sheet.
2. If the excel file is already created but there is no sheet associated with it. QTP will open this file and add the sheet.
3. Say if the file is already created and the sheet is already there, QTP will overwrite the sheets.

Example:


DataTable.ExportSheet "C:\techtravel.xls","flight"

if we have a created a sheet called “flight”
also


DataTable.ExportSheet "C:\techtravel.xls",1

if we want to export the first sheet

Import :- imports the specified Excel file to the run time Data Table
Syntax:-


DataTable.import(location+filename)

Example:


DataTable.import("C:\Test\techtravel.xls")

Import method deletes/replaces all table available in datatable during run with its sheets.Remember sheet1 will be copied to Global,Sheet2 will be copied to Action. If you have more sheets in the source excel there will no Excel tab in QTP.So we need to create those tab by addSheet then only we will be able to get those extra sheets else those data is not accessable using this method.

It is a best practice to know the numbers of sheets present in the source file and try to add those sheets during runtime. Then try to get those sheets in QTP.

Import Sheet :- To import the specific sheet in the run time data table.The data in the imported sheet replaces the data in the destination sheet
Syntax:-


DataTable.ImportSheet ("location+filename", "Source sheet",destination sheet) 

Example :-


DataTable.ImportSheet "c:\techtravel.xls","flight","Global"

here also you need to create a sheet using datatable.addsheet,then only we will be able to put the flight to run time data.
GetCurrentRow :- returns the current row in the first sheet in the run-time Data-Table(Global sheet).if you are using BPT framework or business component driven approach

Syntax :

var x = DataTable.getCurrentRow

Example:


datatable.Import "c:\test\techtravel.xls"
msgbox datatable.GetCurrentRow

GetSheetCount:-returns the total number of sheets in the run-time Data Table Syntax:-


Var x = datatable.getsheetcount

GetSheet :-returns the specifed sheet from run-time Data Table Syntax:- DataTable.GetSheet(“abc”) GetRowCount :-Returns the total number of rows in the longest column in the first sheet in the run-time sheet in the data table(Global sheet) Syntax:- DataTable.GetSheet(“abc”).getRowCount


datatable.AddSheet "abc"
'this will add the temp sheet during run time
datatable.ImportSheet "c:test\techtravel.xls","flight","abc"
'this will import the specific sheet flight to abc
msgbox datatable.GetSheet("abc").getRowcount
'this will give the row count of abc

SetCurrentRow :-set the specified row as the current(active) row in the run-time Data Table Syntax:-


DataTable.SetCurrentRow(value)

example:-

DataTable.setCurrentRow(2)

For the above written cases datatable needs to have atleast 1 row. It will try to set that is having a valid data row SetNextRow:-Set the row after the current(active) row as the new current row in the run-time Data-Table Syntax:-

DataTable.GetSheet("abc").setNextRow

setPrevRow:-set the row above the current(active) row as the new current(active)row in the run-time Data Table Syntax:-

DataTable.SetPrevRow

How to Loop through:

Now we need to read the rows one by one…for this we need to select a particular row first.
the syntax is


datatable.SetCurrentRow(i)
'i is the looping variable
datatable.AddSheet("Sam")
datatable.ImportSheet "H:\Automation\Sam.xls",1,"Sam"
s= datatable.GetSheet("Sam").GetRowCount
For i=1 to s
datatable.SetCurrentRow(i)
Next

Fetch Value from Datatable:


s= datatable.GetSheet("Sam").GetRowCount
For i=1 to 5
datatable.SetCurrentRow(i)
msgbox datatable("Name")
Next

Example:

Write a code that will capture Fly from and fly To drop down values..save to a user defined sheet and later Export the run time sheet to user defined Drive…

dataTable.AddSheet("flight")
' this will add a new sheet at last
sheetcnt= datatable.GetSheetCount()
' this will give the total number of sheet count 
datatable.GetSheet(sheetcnt).AddParameter "Fly From",""
' this step will get the sheet created at last and add parameter
 datatable.GetSheet(sheetcnt).addParameter "Fly To",""
' this step will get the sheet created at last and add parameter
itemcount1=  Window("Flight Reservation").WinComboBox("Fly From:").GetItemsCount
'this will give the itemcount from combobox
For i=0 to itemcount1-1
item1=Window("Flight Reservation").WinComboBox("Fly From:").GetItem(i)
' get items one by one
datatable.setCurrentRow(i)
'setting current row
datatable.Value(1,sheetcnt)=item1
' set value to the datatable
Next
itemcount2=Window("Flight Reservation").WinComboBox("Fly To:").GetItemsCount
For j=0 to itemcount2-1
item2=Window("Flight Reservation").WinComboBox("Fly To:").GetItem(j)
datatable.SetCurrentRow(j)
datatable.Value(2,sheetcnt)=item2
Next
datatable.ExportSheet "C:\Test\techtravel.xls","flight"
'Export datatable to local

Note:Datatable starts with 1 if you are using excel.But Array starts with 0. So we need to be careful while mixing there two.

Code to Read Data From Excel Through QTP or UFT or How to Read Data From Excel Through QTP or UFT?

1st method:


datatable.importsheet "path of the excel file.xls",source sheetID,desination sheetID
n = datatable.getsheet("desination sheetname").getrowcount
for i = 1 to n
columnname = datatable.getsheet("destination sheetname").getparameter(i).name
if colunmname = knowncolumnname then
value = datatable.getsheet(destinationsheetname).getparameter(i)
end if
next
 

The more fine tuned way to code…..

2nd method:


set objexcel = createobject("excel.application")
Set objWorkbook = objExcel.WorkBooks.Open("path of the file.xls")
Set objDriverSheet = objWorkbook.Worksheets("name of the sheet")
columncount = objDriverSheet.usedrange.columns.count
rowcount = objDriverSheet.usedrange.rows.count
for i = 1 to colunmcount
columnname = objDriversheet.cells(i,1)
if columnname = knowncolumnname then
for j = 1 to rowcount
fieldvalue = objdriversheet.cells(j,i)
next
end if
next
 

How to Compare two Sheets?


'The CompareSheets method compares between two sheets.
'if there is a difference between the two sheets then the value in the second sheet
'will be changed to red and contain the string:
'"Compare conflict - Value was 'Value2', Expected value is 'value2'"
'sheet1, sheet2 - the excel sheets to be compared
'startColumn - the column to start comparing in the two sheets
'numberOfColumns - the number of columns to be compared
'startRow - the row to start comparing in the two sheets
'numberOfRows - the number of rows to be compared
Function CompareSheets(sheet1, sheet2, startColumn, numberOfColumns, startRow, numberOfRows, trimed) 'As Boolean
Dim returnVal 'As Boolean
returnVal = True
'In case that one of the sheets doesn't exists, don't continue the process
If sheet1 Is Nothing Or sheet2 Is Nothing Then
CompareSheets = False
Exit Function
End If
'loop through the table and fill values into the two worksheets
For r = startRow to (startRow + (numberOfRows - 1))
For c = startColumn to (startColumn + (numberOfColumns - 1))
Value1 = sheet1.Cells(r, c)
Value2 = sheet2.Cells(r, c)
'if 'trimed' equels True then used would like to ignore blank spaces
If trimed Then
Value1 = Trim(Value1)
Value2 = Trim(Value2)
End If
'in case that the values of a cell are not equel in the two worksheets
'create an indicator that the values are not equel and set return value
'to False
If Value1 <> Value2 Then
Dim cell 'As Excel.Range
sheet2.Cells(r, c) = "Compare conflict - Value was '" & Value2 & "', Expected value is '" & Value1 & "'."
Set cell = sheet2.Cells(r, c)
cell.Font.Color = vbRed
returnVal = False
End If
Next
Next
CompareSheets = returnVal
End Function

Create an excel sheet and enter a value into first cell through QTP/UFT?

Dim objexcel
Set objExcel = createobject("Excel.application")
objexcel.Visible = True
objexcel.Workbooks.add
objexcel.Cells(1, 1).Value = "Testing"
objexcel.ActiveWorkbook.SaveAs("D:\ani.xls")
objexcel.Quit 

How To Pass User Input Values to Datatable in QTP

The syntax to get data from user is as follows:

InputBox(prompt[,title][,default][,xpos][,ypos][,helpfile,context])

Please refer here for more on input box
All datatable methods

DataTable.AddSheet("output")
'Will add a sheet during runtime
user_input=DataTable.GetSheetCount
'Create a variable how many sheets are present during run time
DataTable.GetSheet(user_input).AddParameter "Emp_No", ""
'Adding parameter as employee Number
DataTable.GetSheet(user_input).AddParameter "Emp_Name", ""
'Adding parameter as employee Name
DataTable.GetSheet(user_input).AddParameter "Emp_sal", ""
'Adding parameter as employee salary
For i = 1 to 3
    DataTable.SetCurrentRow(i)
' Setting the currentrow
    DataTable.Value(1,user_input) = inputbox("Please provide Employee Nummber")
'getting Employee number as input and storing that in the first column
    DataTable.Value(2,user_input) = inputbox("Please provide Employee Name")
DataTable.Value(3,user_input) = inputbox("Please provide Employee Salary")

Next

Optionally You can export the sheet to local using the exportsheet method.

Script to Import Data From Database to Datatable in UFT or QTP


Dim con,rs
Set con=createobject("adodb.connection")
Set rs=createobject("adodb.recordset")
con.provider="microsoft.jet.oledb.4.0"
con.open"d:db.mdb"
rs.open"select*from Stud",con
datatable.GetSheet(1).addparameter"STUD_NO",""
datatable.GetSheet(1).addparameter"STUD_NAME",""
datatable.GetSheet(1).addparameter"STUD_PAY",""
row=1
Do While Not rs.EOF
datatable.SetCurrentRow(row)
datatable.Value (1,1)=rs.fields("studno")
datatable.Value(2,1)=rs.fields("studname")
datatable.Value(3,1)=rs.fields("studpay")
row=row+1
rs.movenext
Loop
Database Connection :Microsoft Access database With QTP

The Expert (Database connection) View enables you to access databases using ADO and ODBC. Below is a sample test that searches for books written by an author in the “Authors” table of the database.


Dim MyDB
Dim MyEng
Set MyEng = CreateObject("DAO.DBEngine.35")
Dim Td
Dim rs
' Specify the database to use.
Set MyDB = MyEng.OpenDatabase("BIBLIO.MDB")
' Read and use the name of the first 10 authors.
Set Td = MyDB.TableDefs("Authors")
Set rs = Td.OpenRecordset
rs.MoveFirst
For i = 1 To 10
Browser("Book Club").Page("Search Books").WebEdit("Author Name").Set rs("Author")
Browser("Book Club").Page("Search Books").WebButton("Search").Click
Next

VB script to compare two excel sheets

This is a fantastic code to compare two excel sheets.Basically this can be treated as Lean project.:)


ExcelFilePath1 = InputBox("Please Enter the Path of first Excel File")
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(ExcelFilePath1) = false )Then
msgbox ExcelFilePath1 & " doesn't exist."
wscript.quit
End If
ExcelFilePath2 = InputBox("Please Enter the Path of second Excel File")
If (fso.FileExists(ExcelFilePath2) = false )Then
msgbox ExcelFilePath2 & " doesn't exist."
wscript.quit
End If
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = false
Set objWorkbook1 = objExcel.Workbooks.Open(ExcelFilePath1)
Set objWorkbook2 = objExcel.Workbooks.Open(ExcelFilePath2)
Set objWorksheet1= objWorkbook1.Worksheets(1)
Set objWorksheet2= objWorkbook2.Worksheets(1)
For Each cell In objWorksheet1.UsedRange
If cell.Value <> objWorksheet2.Range(cell.Address).Value Then
'Highlights in green color if any changes in cells (for the first file)
cell.Interior.ColorIndex = 4
'Highlights the same cell in the Second file
objWorksheet2.range(cell.Address).interior.colorIndex = 4
Else
cell.Interior.ColorIndex = 0
End If
Next
objExcel.displayAlerts = False
objExcel.Save
objExcel.quit
set objExcel=nothing
msgbox "It is Done dude"

How To Work With Actions In UFT?

An Action creates a logical division of the flows. So the recorded scripts or the coded scripts can be divided into groups.

Action: A Set of the Statements code block for performing a/a lot of tasks/Tasks. This is done for reusability. However, for a conceptual thing action can be non Reusable as well.
kind of final class in java.

Types of Actions:

  • Non Reusable actions- These types of actions are not reusable, hence they can be used only to a specific test.
  • Reusable actions- These types of actions are reusable hence can be called and reused from different tests.
  • External actions-  Offcourse they are reusable actions by nature but they are saved in a different test. We have two options to use external action.
  1. We can create a noneditable version of the external action. So if we need to modify the script, the original needs to be updated. As there is a single point of truth, I mean there is only one original copy, maintenance is easier.
  2. We can create an editable version by copying it into the local test. But after copy, there will be no connection with the original Action. Maintainance becomes tough if we use this type of Action.

Operations on Actions:

  • Creating Actions(Insert>call to new action>enter name of the action>click ok ..now prepare scripts for those action)
  • Splitting Actions(located default action>Edit menu>action>split action>Enter Action 1 name & action 2 name. Actually we need to create a default action –> create total script–>split the default action into different actions)
  • Renaming Actions(Select the action–>drop down box–> edit menu–>action–>rename action–>modify the name>click ok)
  • Deleting Actions(Select the action–>drop down box–> edit menu–>action–>delete action–>confirm deletion–>click ok)
  • Calling an Action(Insert–>call to existing action–>browse path of the test–>select desired action–>click ok) just we need to remember once called an action we can not edit it.
  • Copying an Action(Insert–>call to copy of action–>browse path of the test–>select desired action–>click ok) After copy we can edit this section as this is reusable.
  • Making an Action Reusable/Non Reusable(Select Non Reusable action >edit >action>action properties>check reusable action checkbox >click ok)

If you are using an action-based framework or trying to add external /reusable action try to use reference or relative path of the action is added.

where can we save the OR files:
1. local drives
2. Can be uploaded to QC

 

How Action Based Test looks like

Test iteration is controlled using Run tab of test settings(navigation–File–>settings) but action iteration is controlled from action call properties.

There are multiple frameworks available on Actions. Combination of Actions and functions. But we must remember, the less the number of actions are inserted, the execution time will be faster. Actions take their own time to load and execute.

How to Check the properties of an Action?

The navigation to get the properties of an Action is as follows:

  • Right Click on the Script Editor | Select Properties
Action Propertise from Script Editor
Action Properties from Script Editor
  • We need to open the solution explorer right click on the script | Select Properties
Action Propertise from Solution Explorer
Action Properties from Solution Explorer

What are the properties of an Action?

The properties of an Action are as follows:

  • Name of the Action
  • Location of the Action
  • Reusable flag to determine if the action is reusable or nonreusable
  • Input parameters for the Action
  • Output parameters for the Action.

How do I create an action template?

If you want to include one or more statements in every new action in your test, you can create an action template. For example, if you always enter your name as the author of an action, you can add this comment line to your action template. An action template applies only to actions created on your computer.

How to Create an Action template in QTP?

To create an action template, create a text file containing the comments, function calls, and other statements that you want to include in your action template. The text file must be in the structure and format used in the Expert View.

Save the text file as ActionTemplate.mst in your dat folder. All new actions you create contain the script lines from the action template.

Difference between Action and Function:

Action and Functions are two important aspects of UFT or QTP. Here is the difference between them.
This is also a popular UFT or QTP interview question.

General differences:

  • We can use actions within QTP/UFT. Actions are purely built-in features of UFT, whereas we can use functions anywhere(i.e. in any programming language like VBScript ).
  • We can call functions within actions but we can’t call actions within functions.
  • Generally, functions are saved with “.vbs” or “.qfl” extension (if written in an external file)we execute those files or add in the test and call the function. whereas actions will save with “.mts”.
  • Actions – can only accept primitive data types as parameters (strings, integers, etc)  whereas Functions – can accept anything depending on its parameter value and usage.
  • In Action parameters always are passed by value only whereas in Functions, we can have pass by value or pass by reference.
  • Actions, depending on the configuration may or may not be reusable whereas by default the functions are reusable.

5)Resource Usage

Actions – For each action, there’s a folder, three separate VBS files, a local Object Repository, a subfolder containing snapshots, an Excel spreadsheet, and a few seconds of load time. Functions – There’s the code contained in the Function.

6.API

Actions – we cannot insert calls to Existing Actions through the QTP API, you can only do it through the interface. Functions – we can attach Function Libraries to Test Scripts through the QTP API
Another API implementation- How to Call Reusable API Script From GUI Script in UFT The popular use is to connect QTP with QC.

7.Return Values

Actions – Return values are difficult to understand and read in the syntax. Mostly UFT/QTP can understand that. Functions – Return values work as they do in other languages as I wrote earlier this depends on parameter value.

8.Others:

  • we enhancing the scripts(Checkpoints, output values)insert in the action the actions allows but in the case of functions it doesn’t allow the enhancing the scripts.
  • In the case of call copy action, it won’t reflect into the child’s action to parent action but functions it will reflect into the child’s action to parent action.
  • Mainly very important use:if at all call the Action the particular object information stored into the object repository but in the case of function whenever we call the function it doesn’t store into the object repository.

I suggest using the function-driven approach rather than action-driven. Actions are tightly integrated with QTP. So the migration of the project will be easy.

How to use comment in UFT?

Comments play an important role in UFT scripting. It gives a clear idea of what we are trying to do with the UFT script.

Comments are an integral part of code development in automation framework. So as the Documentation. Comments enable us to create proper documentation in the script. Adding good comments to your code is only one aspect of writing readable and maintainable code.

Good code is always self-explanatory and self-documenting. A comment generally answers the following questions:

  • Programmer’s intention for writing the code.
  • The actual purpose of the script.
  • With respect to the overall scheme of the script, where does this piece of code stand?

Documentation via comments helps many ways:

  • It helps new developers or reviewer to understand the code easily.
  • It helps the existing developers to understand the purpose of the code, who wrote it, what are the arguments, What are the revision history, what are the prerequisite, etc.
  • Comments can make scripts more understandable, more readable.
  • Comments also make debugging easy.

Good comments are generally paragraph-level comments. Few features of a good comment-

  • No line by line commenting. The code should be clean enough to make the reader understand.
  • A comment should clearly and quickly convey the purpose of the code.
  • A comment should stand for the guideline of the code.

Bad comments are those comments which are redundant. They add more clutter in understanding. As a result, they actually do more harm than good.

We can make some code to run and commented code remains un-executed. If you are using static testing, this feature is your friend.

Hence it is always better to provide comment in our script and this section talks a lot about our code.

Comment syntax is not exactly an operator or a variable but works as an ignore line or lines operator in UFT or QTP or VbScript.

WSH or VBScript engine ignores the comment statements during script execution.

Syntax of a Comment in UFT, QTP, VBScript:

This section displays details on

  • how to add comments in VBScript?
  • how to add comments in UFT?
  • how to add comments in QTP?
Rem Statement

Rem statement (After the Rem keyword, space is required before comment.) can be used to comment a line.

It can be given at the beginning of the line like-


Rem to get values from FlyCombo
Windows("xyz").FlyCombo("abc").getValue()
 

Or

It can be given after a valid line. like


Windows("xyz").FlyCombo("abc").getValue() Rem to get values from FlyCombo
 

how to comment in VBS file?

Apostrophe or single quote is treated as a comment (‘).


'Windows("xyz").FlyCombo("abc").getValue()
 

Once the WSH gets the single quote, it ignores the line.

Other Usage of Comments

We can create Template of Script, or function or methods or class using proper comments.


'******************************************************
'Script Name: MyScript.vbs
'Author: Mr X and techtravelhub.com
'Created on:29-Mar-2017
'Description: This script will do so and so operations
'History: 
'       Rev-2: Animesh did change so and so variable
'       Rev-1: Mr X and techtravelhub.com created the initial script
'******************************************************
'initialization section
----
----
'Main body
----
----
'procedure section
----
----
'teardown section

Comment/Uncomment a block of statements

  • Select the block of statement and use the short cut key Ctrl + M (for comment)
  • Select comment block and use short cut key Ctrl + Shift + M (for uncomment)

Purpose of comments in VBScript or UFT or QTP:

  1. We can use comments for making the script understandable hence comments provide code clarity.
  2. We can use comments for making one or more statements disable from execution.
  3. Indent code along with comments make the code readable later.
  4. Using comment we can use white space effectively.
  5. Organize code into logical blocks distinguished by logical comments.

Note: As the English proverb goes too much of good things is never good. It holds good for comment as well. We need to use the comment in such a manner that it should short, understandable, comprehensive and to the point.

Otherwise, the purpose of using comment goes down. The code will become to many junk statement with less Value-added code.

Synchronization Concept in UFT

UFT provides different strategies to work with synchronizations.

How to work with Capture Events in UFT?

Capturing events is helpful when we are working with different events mainly in ajax is getting fired.

Enable different Events in QTP :

while creating a dynamic (QTP) webpage developer must have given few touches of DHTML effect or scripting(Javascript/vbscript). The effect may be few triggers that will invoke something,may be a page loader,may be a color change,may be click event,double click event etc.
Examples of events could be:

A mouse click
A web page or an image loading
Mousing over a hot spot on the web page
Selecting an input box in an HTML form
Submitting an HTML form
A keystroke
Please refer http://www.w3schools.com/js/js_events.asp this for more event information.
Now to capture the web events more smoothly QTP has given the below option to the user….

Enable the ondblclick event in the Web Event Recording Configuration
To enable special event handling, use the Web Event Recording Configuration utility.
1. Go to Tools -> Web Event Recording Configuration.

How To Capture Events in QTP?

2. Click .
3. Expand the Standard Objects branch.
4. Select the object you want to configure.
How To Capture Events in QTP?
5. Go to Event -> Add -> ondblclick. The event will be added to the list on the right.
6. Select “If Handler” in the Listen column.
7. Select “Enabled” in the Record column.

How To Capture Events in QTP?
8. Click to close the dialogues.
Follow the steps while you are recording one script. Hope this will help you to capture different kinds of events on a webpage.

Test Run

A test run is a method by which UFT mimics the user by providing the keyboard or mouse operations to the application without manual interventions.

UFT supports three run modes. They are as follows:

  1. Normal Run or Run
  2. Maintenance Mode
  3. Update Mode
Normal Run Mode

Normal run mode is the default run mode for UFT. It just verifies the current behaviour of the application with the expected one and finds the differences. The test is passed when actual and expected results are the same but failed if they differ.

Below are the steps we need to perform to run a test:

  1. If UFT is not opened, we need to click on the shortcut or need to go to start->Programs->HP tools->UFT and click on UFT to open the UFT.
  2. We need to open the test that we have just recorded or enhanced.
  3. We need to verify if all the images are saved to the test result. For this, we need to choose Tools->Options and select the Run settings. The Save steps Screen Capture to test results option needs to be set as always.
  4. Start running the test.
Maintenance Mode Run

Maintenance mode run allows our tests to run and using various inbuilt techniques, it suggests the process of updating our steps, object repository etc. For updating any scenario, the UFT opens up several corresponding windows and several screens.

Update Mode Run

Update mode run allows us to update tests or components. We need to run component to update the test object description. We can update the data for an entire component or only the part of it. However, it is dependent on which run and debug mode we choose. Once we finish updating the data, the updated data is used in subsequent runs.

Note: While UFT updates the data or components, it is generally gets saved in local object repository even if the object belongs to the shared object repository. Remember, local object repository is having higher priority over shared object repository, hence in all subsequent runs UFT will pick up the updated local object repository.

Test Batch Runner

Test Batch Runner in the UFT’s feature that allows us to run scripts in a batch mode.

Debugging tests

After enhancing the test , now , we need to check, if , it is working fine. or else we need to debug the script. Debugging the test ensures that it is working smoothly without any interruption.Debug will ensure the logic and syntaxes are correct. In Order to detect and isolate the faulty component or the area of the script, we can use the following components

  • Step Into
  • Step Over
  • Step Out
  • Breakpoints
  • Add to watch
  • Pause

Before you proceed further, as UFT is based on VBscript, the maximum syntax and looping abide by the syntaxes of VBScript. So we need to deep drive to VBScript a little bit,

How to Debug a UFT script in VBScript Debugger?
How to Debug a UFT script in VBScript Debugger?

How to Debug a UFT script in VBScript Debugger?

For effectively resolve the error, we need to use the debug process of VBScript or UFT. It is a feature given to any IDE (Integrated Development Environment). Debugging refers to an activity to effectively figure out the root cause of any problem. The problem could be anything:

  • A Bug
  • A logic error
  • A mismatch in requirement
  • A wrong understanding.

It is very important while debugging and learning an Automation framework.

What is Debugging?

Debugging is a process by which we try to detect, locate and omit bugs from our code.

What is Debugger?

A debugger is a two-step process:

  • Identifying an issue
  • fix the issue and retest

A debugger is a tool (a set of codes) that provides insight into the running code in line by line manner. It places itself between compiler or runtime engine and real running of the program.

Even though the main objective of a debugger is to debug and find the issues in the code. But it is equally effective to understand the code, in terms of a logic flow. Without debugging if we need to read and understand the code, it would be a time-consuming process.

Let’s see another important process called maintenance. During this phase, most of the time the person who wrote the code does not fix the code or alter the code. Without a proper debug process, maintainability will go for a toss.

UFT Debug Process

UFT does have a solid debugger which will help us to debug. This post will not talk about UFT debugger but I will discuss how we can debug.QFL or.VBS file outside of the UFT IDE.

Microsoft Debugger

Microsoft Script Debugger is a correct tool that can be used as a debugger of a VBScript file on a system where UFT is not installed.

How to get Microsoft Script Debugger?

UFT/QTP has the debugger inbuilt with the IDE. In case if we are using UFT to debug our scripts, we do not need any other component or debugger.

Just in case, if we are debugging the.VBS file outside of UFT or we want to debug the.VBS file where UFT is not installed, We need to download the Microsoft Script Debugger from here.

After downloading, we need to install the debugger. As it is a Microsoft product, it is safer to restart the machine to take effect.

How to activate Microsoft Script Debugger?

The Microsoft debugger upon installation, attached to itself with WSH.Once we double click on the required.VBS file, the script will execute it via Microsoft Script Debugger.

We have one more option to use debugger via command line. To activate this feature we need to go to Start->Run->CScript.exe and open it.

Once we have opened it, we can use different switches to execute. Switches can be found here.

Microsoft Script Debugger has a great visual representation along with the components mentioned below.


WScript //x {path of the script}
//or
WScript //d {path of the script}

//x switches ask WSH to bring debugger and breaks at the first line.
//d switches ask WSH to bring the debugger if it is needed. It activates the debugger at the preset breakpoint.

Components of Microsoft Script Debugger

BreakPoint:

This is the important component of the Microsoft Debugger. This will pause execution at a certain line if we use this component and enable it. The objective of the breakpoint is to instruct the WSH engine to stop the execution at the given breakpoint. This component is very useful as it only halts where we want it to halt leaving other lines of code unhalted but executed.

We can open the debugger manually and click on the suspected line. This is the line where the execution will halt. This feature is also available in UFT IDE. This line will be highlighted in yellow and a red circle or dot will indicate the execution is paused.

If we open the script using //x switch, the debugger automatically stops at the first line of the script.

We can set up multiple breakpoints in the script.

With Breakpoint enabled WSH will only stop if one of the below occurs:

  • It encounters an unhandled error
  • It reaches the end of the script.
  • It gets a breakpoint provided by the user.
Stepping

While breakpoint pauses the execution, these stepping features enable us to go slowly over the line of codes to identify the issue or understand the code.

Stepping is divided into three parts:

  1. Step into
  2. Step over
  3. Step out
Step Into

This component enables us to go into a user-defined procedures, sub or a function. However, we can not go into a function or sub defined by VBScript.Like Msgbox().So to step into a function or sub, the function or sub has to be in the scope of the debugger.

This component goes inside of a custom function or sub or procedure. It starts executing line by line.

Step Over

Once we know the function is good to go, we can use this feature/component. This component instead of going inside the function or sub or procedure, executes them and provides the output directly to the user.

Step Out

This feature finishes the execution of a lower-level procedure or sub or function. It then pauses at the starting of the next line. This is extremely useful when we step into a function or procedure and decide to leave or go out of it.

Note:

Step into, Step over, Step Out are just visual representation and stoppage of execution but underlying execution still takes place even if we skip from one component to another.

View Call Stack

This component stacks the nested sequence of function or procedure calls. It provides a hierarchical list of the chain during the execution of our script. It is useful when we have multiple function calls in a chained manner.

WSH engine keeps track of all the calling function’s order until these functions get completed. WSH traverses through the stack to determine the completion of the called functions.

How to Activate Call Stack?

Below steps needs to be performed while activating the call stack.

  • Put a breakpoint in the script.
  • Run the script in the debug mode.
  • While the control stops at the breakpoint, click on the call stack option under view Menu.
  • The call stack window will appear and displays the stack information.

As it is a stack, we need to read from the bottom towards up.

Command Window

This component enables us to query and view active variables. This is very useful when we want to check some value of the variables, functions or sub. So theoretically, it is another strong debugging feature. The command window supports a special technique by which we can query the WSH.

We need to use the “?” question mark to query the WSH. The “?” operator fetches the required information if available in the scope of WSH.The breakpoint and? operator combo provides a powerful technique to view the insight of the script.

Command window can access the intrinsic objects like Err Object. The WSH also has a set of other intrinsic objects available.

Inserting temporary code

Debug mode in Microsoft Script debugger supports to insert temporary custom test code during execution in debug mode. This helps us to test the logic, variable value, flags, etc. This is a very popular technique while debugging and testing a large codebase.

 

How to Use Debug Message?

The debugger provides a clear insight into a code. While watching/view are temporary and only available during test run/debug session, the debugger provides other ways to save the debug message.

    • Put the debug message to a log file for future reference. A redirecting debug message to a log file is an efficient way for framework development.
    • This is running commentary of the script execution about how and what the script performing from running an Excel macro to a sendkey function.
    • Debug messages enable us to track changes of a variable which we can configure and see how the values are getting changed.
    • The simplest form of debug message is Msgbox() function. It is a great tool to see values. It also pauses the script execution in a modal way until and unless we click on the “Ok” button. The script execution remains halted until then.
      
      Msgbox "The value is "+myVar
      
    • The WSH Script uses the Echo() method to display detailed information. It is more preferable over the Msgbox() function. In WScript.exe, Echo method will display the message in a dialog box. If we use several Echo() messages, in our script, we need to click ok again and again.

WScript.Echo "The value is "+myVar
  • The Stdout property of WSH is another feature to transfer TextStream to console. This is only applicable to CScript.exe. In the case of Wscript.exe, Stdout property is not applicable and throws an error.
  • LogEvent() is another method of WSHShell object to log the WindowsEvent log. This method is supported by both WScript.exe and CScript.exe.

What is not supported by Microsoft Script Debugger?

The Microsoft Script Debugger does not support the followings:

  1. A local window to showcase active variables at the breakpoint.
  2. It does not have a watch window
  3. It does not support dynamic breakpoint

Note:

UFT/QTP does have these features, so if we are using UFT/QTP instead of Microsoft Script Debugger, these components will be automatically available

The omission of Assertion in UFT and VbScript Debugger

VBScript Debugger or UFT surprisingly does not support the assertion. Also, there is no support for AssertThat() function. We need to depend on if-else and custom message to implement assertion.

Conclusion:

While UFT provides a great debugging option, Microsoft Script Debugger is a lightweight debugger that can debug any VBScript used in UFT. It can also work in a UFT neutral system. This feature is a major boost for the Script review process. Surely and certainly Microsoft Script Debugger will increase the speed of review, execution and debug process.

VBScript concepts for UFT Automation testing.

UFT is based on VBScript. It is also required to learn VBScript a little to upgrade UFT scripts.

How to debug UFT script in VBscript debugger?

The tips of tricks of debugging a complex script is very important.

Errors and Error Handling in VBScript

Errors and Error handling is another component that whose knowledge minimizes the maintenance effort.

Defining and exporting test results

Now after the running of the test we need to collect the test results.

How to work with reporter Object?

Reporter Object is very important point to understand reporting via UFT.

Analyzing results:

In this phase we analyze the test results(the passes,fails and warnings). An execution of test may fail due to various reasons. They prime causes are as follows:

  • Checkpoints failed
  • Script error
  • Script could not run due to some external error.
  • Syntax error

In case, Script has passed, it will appear in the result as green. In case script has failed, i n result it will appear as red. For script error , the report may be in warning (color-orange).

Navigation to Report:

Automation menu–>Select Result

By default the UFT will show the latest execution report.

UFT step result
UFT step result

Lets understand the UFT report bits and pieces:

  • The left hand pane displays the test result tree.It is an icon based view of the steps.If the icon does have a + sign associated to it. It signifies that the icon or object can be further expanded. Once we click on the + sign it will further drill down to the steps. Each run in UFT is called iteration. For each iteration the same tree will be created. Iteration has a number associated to it.
  • The right pane shows the test results. It has an iteration summary table. The summary table indicates which iteration has passed and which one is failed. So the summary will tell us how many checkpoints are passed or failed.
  • The last table shows the status summary. It provides an overall view of the passed, failed and warning numbers.
  • The last component of the test result is the active screen. It just shows the screens on which the steps have been performed.

If we want to customize the save images then, we have the following options:

  1. Always
  2. For errors
  3. For errors and warning
The details of Test Tree symbols
GUI ElementDescription
rightThe step has passed. It is applicable for tests where a checkpoint or micpass command is attached.
FailedThe step has failed. It is applicable for tests where a checkpoint or micfailed command is attached.
WarningThe step has completed but having some issue. It is not equivalent to failed.
failed unexpectedlyThe step has failed unexpectedly. Like object not found.
WarningInformational step or optional step. It is nothing to do with fail or pass status.
Smart IdentificationThis symbol indicates that the object was found by activating smart identification.
recovery scenarioThis symbol indicates that the script activated recovery scenario.
stoppedThis symbol indicates that the script execution is stopped forcefully before it’s actual end.
dynamic test object creationThis symbol indicates that the test object is not present in the object repository and may have been created using code.
maintenance modeThis symbol indicates the maintenance mode run result.
How to jump to a step in UFT run result?

We can view the step in UFT that corresponds to a node in the run result tree. To view the step in the test that corresponds to a node , we need to perform the following steps:

  1. We need to select a node in the test result tree.
  2. We need to perform one of the following tasks
  • We need to click the Jump to Step button available in the Run Result toolbar.
  • We need to right click and select Jump to Step from the context sensitive menu.
  • We need to Select View–>Jump to Step

The UFT is activated and the step is highlighted.

For a successful Jump to a Step, the following conditions should be always true.

  • UFT should be up and running.
  • The test must be opened whose results are displayed in the test result window.
  • The test must run in an UFT which supports Jump to Step functionality.
  • The node should have a corresponding step in the script. However note that the feature is disabled for the Action,Iteration,Runtime data table,Test Summary nodes.
  • The recovery scenario has not been performed on the step we are targeting.
  • The step has not run via command tab or watch tab of the debug viewer.
  • The step was not part of an action which was triggered by the LoadAndRunAction command.
  • The test is saved before run session.
  • The test is run in normal mode.

So many conditions to find a step?? No dude. I do not suggest this steps. Rather you can check the result and by debugging you can find the test. Try not to use automatic step finder, instead we need to use logic to find the step.

Test reporting:

In this phase we report as per SLA criteria.The execution report we received in the previous step can be analyzed manually to report any issues. If the UFT is attached to QC or ALM , we can export the failed test as bug.

To log a defect we need to navigate :

Test Menu–>Tools–>Select the issue–>Add defect

We can export the test result details to the following formats:

  1. HTML
  2. PDF
  3. DOC

This means whenever the test result viewer is not available, we can view the results in the above written formats. A popular example and reason to export one of the format is when we send the test result over network via shared drive or email. In that case, in that machine the UFT run result viewer may not present. These formats come handy then.

We need to go to Export Report submenu. the export report has the following conditions:

  1. Export Range (All or selection)
  2. File Type(HTML,PDF,DOC)
  3. Export format(short,detailed,user defined XST)

How to write custom HTML file?

Refer the post in URL to know in detail on how to write custom HTML reports.

Viewing System monitor results

The system monitor tab in the test result window shows how the system was behaving during test execution. It is not widely accepted monitoring tool. We can safely ignore this feature.

Defect Reporting using companies defect management system.:

In this phase ,we log defects in defect management system like-excel,bugzilla,QC etc.

Modifying tests:

After the defect fix or a case of new build we generally modify our tests.Why it is required??? just to save ourselves from pesticide paradox.

Performing re and regression testing

In this phase we generally run performance and regression testing again.

Advanced UFT topics:

How to Capture Events

Read here for capturing events.

Introduction to Dictionary Object

Dictionary object is the list containing key value pairs.

How to work with Optional Step?

An optional step is a step that is not necessarily required to successfully complete a run session. During a run session, if a step in an optional dialog box does not open, QuickTest bypasses this step and continues to run the test. When the run session ends, a message is displayed for the step that failed to open the dialog box, but the step does not cause the run to fail.

What is automation framework?

Automation framework is the next thing we need to know.

Regular expression in UFT

Regular expression in UFT allows to work with patterns for input and output verifications.

Assets of UFT/QTP with Extension

Test AssetsExtension
Test File.mtr
Shared Object Repository.tsr
Local Object Repository.mtr
Test Batch runner.mtb
Recovery scenario.qrs
Function Library.qfl
Results.xml

 

Transactions in UFT

Transaction is a technique to measure how long it takes to run a section or part of the script in our test. A transaction represents the process in our application that we are interested to measure. A Transaction can be inserted anywhere of the code in our test .

Most importantly transactions should be placed within the same action. Transactions are mostly placed around a point where some sort of transaction is happening.

During the test execution, the start transaction provides a signal for beginning of a time measurement. It also soft signals that a transaction is also underway.  The timer will keep updating till it gets the end transaction signal. End transaction also soft signals that the a transaction is typically over. The report will display the time for a transaction to happen.

How to insert a Transaction

A transaction must have two components.The components are:

  • Starting of transaction
  • End of transaction.
Start Transaction

To insert a start transaction we need to perform the following steps:

  • We need to click or select on the step where we want to put a start transaction. The same page or window is displayed on Active Screen tab.
  • We need to click on Start Transaction button or choose Insert->Start Transaction. The Strat Transaction window will open.

We have to provide the below:

  • A meaningful name for the transaction like-MeasureDatabaseConnectionSpeed
  • Where to insert the statement(before current step or after current step)
  • we need to Click on ok .

In keyword view we can see the code similar like-

Services.StartTransaction "MeasureDatabaseConnectionSpeed"
End Transaction

To insert end  transaction we need to follow the below steps:

  • We need to select the step where we want to end the transaction.
  • We need to click on End Transaction or click on Insert->End Transaction. This will open up the end transaction dialog box.
  • The window will contain all the transaction name we have created during our script development.
  • From the drop down we have to choose the transaction name we want to end.
  • There are two options to place the end transaction code. (before the current step and after the current step).
  • We need to click ok to end the transaction.

In keyword view we can see the code similar like-

Services.EndTransaction "MeasureDatabaseConnectionSpeed"

Very best Techniquesda in QTP/UFT Automation

  • Begin your automation function only when AUT (Application under Test) is stable. ie You should really have done initial spherical of handbook testing in advance of beginning QTP automation activity.
  • Use reusable actions wherever achievable.
  • Do not copy and paste checkpoints when you would like to check exact point in more than just one sites. As a substitute, build different checkpoints. Mainly because manipulating checkpoints in QTP is not feasible or it will be hard.
  • Open up browser / application right after opening QTP.
  • Your vbscript capabilities really should not have any difficult coded item names, the name of the objects should be handed as operate argument.
  • Use Shared Item Repository. My recommendation is do not use DP (Descriptive Programming) which will maximize your maintenance do the job.
  • Before introducing any object to Object Repository, set up ideal object identification attributes (in Resources-> ObjectIdentification) if you feel that default identification qualities are not suitable for you software. If you do it just after incorporating some objects to the Item Repository then you could facial area issues similar to having Many Exam objects in Item Repository for a solitary actual Item.
  • Open up QTP working with the Automation item model. You can do it just by writing ( even you are acquiring ‘ script’ solution in the QTP IDE by itself ) simple .vbs file, and then open up QTP just by double-clicking this .vbs file. It is quite pretty vital if you are building your scripts in a person device/atmosphere and arranging to operate/execute it in another atmosphere. By applying the Automation Object model we are creating guaranteed that all the IDE options (eg Item identification attributes) that are adjusted in enhancement ecosystem are propagated to the execution ecosystem also
  • Normally use Reference / Relative path when calling any external reusable motion rather than employing complete/full path, In any other case, the script will fall short when positioning it in the various paths.
  • Remember to get backup of Item Repositories in advance of rising object repositories.
  • Put good inline responses and also place summary opinions ( description, enter & output parameters, dependency, author ) at commencing of the Examination. In the comments try to remember to mention execution/facts move.
  • Rename the Objects in Item Repository to have suitable that means for them. Due to the fact, the default identifies supplied by including the objects by recording or manually may possibly not be great/meaningful.
  • Give interest to synchronization (ie use of sync, waitproperty, exist). And also use the normal expression the place expected. Or else consistency of script execution will be influenced.
  • Use restoration circumstance to handle any unpredicted conduct ( eg showing pop-up windows occasionally ) of the software.

How to Use a Parentheses in QTP or UFT?

Parentheses or Cannot use parentheses when calling a Sub or Call a Function in UFT
Parentheses in UFT or VBScript

Using of parenthese in UFT/QTP or VBscript is different than other programing languages. This post talks about how to Use Parentheses in UFT or QTP,How to Call a Function in UFT,how to Call a subroutine in UFT. After reading this post I hope you will be clear on where to use parentheses and where not to use parentheses.This post also tells why the issue-“Cannot use parentheses when calling a Sub” comes and How to resolve Cannot use parentheses when calling a Sub error.

What is the meaning of Parentheses in VBScript or UFT?

Parentheses are mostly used in subroutine calls,function calls,array declarations,array accessing, evaluating part of expression,passing value by ByVal or ByRef.

Lets see theses example one by one.

Parentheses in Subroutine and Functions

General Idea about parenthese

To achieve the desired result and to avoid errors, it is important that you use parentheses () correctly in your statements. For more information, see below…
You must use parentheses around method arguments if you are calling a method that returns a value and you are using the return value. For example, use parentheses around method arguments if you are returning a value to a variable, if you are using the method in an If statement, or if you are using the Call keyword to call an action. You also need to add parentheses around the name of a checkpoint if you want to retrieve its return value.
Tip: If you receive an Expected end of statement error message when running a step in your test, it may indicate that you need to add parentheses around the arguments of the step’s method.
Following are several examples showing when to use or not use parentheses.

Impact of parenthese on Subroutine

A subroutine is a group of statements that does not return any value. A subroutine may or may not take arguments. So based on arguments , subroutines can be classified into two broad categories:

  1. Subroutine with arguments
  2. Subroutine without arguments

Let’s look into the structure of subroutines with argument

Sub MySub(sName,intTotal)
//body of the sub
End Sub

In this case (Subroutine) since it is accepting arguments, they need to be inside parentheses. This is the standard structure syntax of Subroutine.

Let’s look into the structure of subroutines without argument

Sub MySub
//body of the sub
End Sub

How to call the Subroutine?

There are two ways to call a subroutine. They are as follows:

  1. Directly by name.
  2. Using VBScript’s call keyword
Calling directly by subroutine name

While calling a subroutine by its name, we do not need to pass any argument, so we do not need any parenthese.

Example:

MySub

For calling subroutines with arguments, we still do not need parenthese. The arguments are separated by comma(,).

Example:

MySub "Test",10
or
MySub sName,intTotal

In case you call a subroutine with parenthese,you will get runtime error “Cannot use parentheses when calling sub”.This is the main reason why we get Cannot use parentheses when calling a Sub issue.

Using VBScript’s Call keyword to call a subroutine

The use of keyword ‘call’ is purely optional when we to call a subroutine. Call keyword is only applicable when the subroutine accepts arguments and they are enclosed in parentheses. In case our subroutine does not accept any argument, there is no need to use parentheses.

Example:

Call MySub
Call MySub(sName,intTotal)
Call MySub("Test",10)

Parenthese on Function:

Let’s look into function now. function is a group of statements that can return some value. There are two possible ways we can call a function.

  1. By using name
  2. By Using VBScript keyword-Call
Calling a function by using directly Name

When we call a function that does not have an argument or any return value, we can use the followings

MyFunc
MyFunc()

In case the function has some argument and does not return any value we can use the following:

MyFunc sName,intTotal
MyFunc "Test",10

Scenario changes when our function has some return value:

val=MyFunc
val=MyFunc()
val=MyFunc(sName,intTotal)
val=MyFunc("Test",10)

In this case, If you have one or more arguments, then it is a must to use parentheses.

Using Call keyword to call a function

If a function has arguments,you must need to put parentheses while using call keyword. the arguments are separated by commas.

Note: If you use Call keyword to call a function, it can not return a value.

Example

Call MyFunc(sName,intTotal)
Call MyFunc("Test",10)

This is how we Call a subroutine in UFT.

Parenthese on Array

Parentheses can be used on Arrays in VBScript.

Dim myArray(3) ' will create an array of size-4

We can access any array element by using parenthese, like

Val=myArray(0)

Impact of Parentheses on Expression

Parentheses can be used to change the priority of an arithmetic expression. Like

(2+4)*3 evaluates 18 instead of 14

Impact on ByRef and ByVal

VBScript supports ByRef and ByVal keywords to specify the parameters passed either by reference or by value. When arguments are passed by value,any change inside the function/sub will not carried to outside of the scope.

On the other hand, if arguments are passed by reference, the changes to the variable becomes permanent and are available outside of the functions/Subs.

By default,all values are passed by reference.

Sub MySub(y) //by default pass by reference
y="Test default"
End Sub
Sub MySub(ByVal y) 
y="Test By val"
End Sub
Sub MySub(ByRef y) 
y="Test by ref"
End Sub
y="hello"
MySub(y)
msgbox y
MySub(ByVal y)
msgbox y
MySub(ByRef y)
msgbox y

Test these and let me know in comment what is your output.

How to Use a Parentheses in QTP or How to Use a Parentheses in UFT?

To achieve the desired result and to avoid errors, it is important that you use parentheses () correctly in your statements. For more information, see below…
You must use parentheses around method arguments if you are calling a method that returns a value and you are using the return value.

For example, use parentheses around method arguments if you are returning a value to a variable if you are using the method in an If statement, or if you are using the Call keyword to call the action. You also need to add parentheses around the name of a checkpoint if you want to retrieve its return value.

Tip: If you get an Expected end of articulation error message when running a stage in your test, it might show that you have to include brackets around the contentions of the progression strategy.Call a Function in UFT also follows the same principal.

Following are a few precedents appearing at use or not utilize brackets
The following example requires parentheses around method arguments since it returns a value to a variable.

Set WebEditObj = Browser("Mercury Tours").Page("Method of Payment").WebTable("FirstName").ChildItem (8, 2, "WebEdit", 0)
WebEditObj.Set "Example"
The following example requires parentheses around method arguments, since Call is being used.
Call RunAction("BookFlight", oneIteration)
The following example requires parentheses around method arguments, since the method is used in an If statement.
If Browser("index").Page("index").Link("All kind of").WaitProperty("attribute/readyState", "complete", 4) Then
Browser("index").Page("index").Link("All kind of").Click
The following example requires parentheses around method arguments, since it returns the value of the checkpoint.
a = Browser("MyBrowser").Page("MyPage").Check (checkPoint("MyProperty"))
The following example does not require parentheses around the Click method arguments, since it does not return a value.
Browser("Mercury Tours").Page("Method of Payment").WebTable("FirstName").Click 3,4

The following example requires parentheses around method arguments, since it returns a value to a variable.

Set WebEditObj = Browser("Mercury Tours").Page("Method of Payment").WebTable("FirstName").ChildItem (8, 2, "WebEdit", 0)
WebEditObj.Set "Example"

The following example requires parentheses around method arguments, since Call is being used.

Call RunAction("BookFlight", oneIteration) 

The following example requires parentheses around method arguments, since the method is used in an If statement.

If Browser("index").Page("index").Link("All kind of").WaitProperty("attribute/readyState", "complete", 4) Then
Browser("index").Page("index").Link("All kind of").Click

The following example requires parentheses around method arguments, since it returns the value of the checkpoint.

a = Browser("MyBrowser").Page("MyPage").Check (checkPoint("MyProperty"))

The following example does not require parentheses around the Click method arguments, since it does not return a value.


Browser("Mercury Tours").Page("Method of Payment").WebTable("FirstName").Click 3,4

Let me know what do you follow to Call a Function in UFT? or Call a subroutine in UFT?

Now lets see why we get cannot use parentheses while calling a sub error-Microsoft VBScript compilation error ‘800a0414’

Definitely, we have invoked a subroutine without a call statement but may have used parameters. So the best way to resolve this issue while calling a subroutine without a call statement , do not use parentheses.

How to correct cannot use parentheses while calling a sub error-Microsoft VBScript compilation error ‘800a0414’? or How to resolve Cannot use parentheses when calling a Sub error?

  1. Use call statement to invoke the subroutine.
  2. Remove parentheses from the subroutine invocation.
Final note on parentheses

When you enclose a procedure’s arguments in parentheses, you must use the call statement and when you remove call keyword, you must remove parentheses. This concept is also helpful to design your framework in automation. Let me know your views on Call a Function in UFT or Call a subroutine in UFT or How to resolve Cannot use parentheses when calling a Sub error by commenting below.

Ref:
MSDN,StackOverflow-1537819,StackOverflow-14902134,Call Statement-MSDN

How to Capture Tool tip Through QTP or UFT Script

Most of the time we use to get this requirement that we need to capture tool tip through QTP. Sometimes we need to check a page with the tool tip.
In the web, this is a very powerful tool to work with automation. we can say in other words in automation in checkpoints it is really a great tool to verify a page, table, image.
Below script is for capturing tool tip of the textbox in Google Site.


msgbox getToolTip
Function getToolTip()
SystemUtil.Run"iexplore","http://www.google.com/"
tooltip_name=Browser("name:=Google").Page("title:=Google").WebEdit("name:=q").Object.title
getToolTip= tooltip_name
End Function

What are GetROProperty,GetTOProperty,GetTOProperties and SetTOProperty in UFT?

Developers develop an application with different elements in any technology.They provide or maintain some basic information about the element.
Now While automating such an application using UFT/QTP, we rely on UFT/QTP.It has its own mechanism to identify and learn about such properties of the application. These are standard object properties.
To begin with, let us understand a few basic things…

  • TO–Test Object[standard]
  • RO–Runtime Object[standard]
  • Get–To fetch some value [kind of getter]
  • Set–To set some value [kind of setter]

 

Mercury now HP has created or defined Test objects according to the supported environment (web,ERP,Java etc).When UFT/QTP records an application,it tries to match the same list of properties for an Object and store them in Object Repository.

Navigate to Tools–>Object Identification
you can see the HP given/created Test Object properties:

For quick and steady access UFT/QTP stored them in registry as well:
The Path would be:
HKEY_CURRENT_USERSoftwareMercury InteractiveQuickTest ProfessionalMicTestTest Objects<<ObjectName>>Properties
or
HKEY_LOCAL_MACHINESoftwareMercury InteractiveQuickTest ProfessionalMicTestTest Objects<<ObjectName>>Properties
depending upon license and installation.
For Browser
HKEY_CURRENT_USERSoftwareMercury InteractiveQuickTest ProfessionalMicTestTest ObjectsBrowserProperties

However all these properties can be found under Help section of UFT/QTP.

In this post I trying to clarify different operation can be made through UFT/QTP on these objects.

 
GetROProperty:
When we do little advance programming in UFT/QTP, We need to fetch the value from the UAT. That becomes a standard requirement in UFT/QTP. Fetching value from application during run time was not so easy.UFT/QTP’s advance programmer made it easy for all of us.

The technique is named as GetROPropery [Get Run time Object Property]

This command deals with the current value of the element.This can fetch values associated with runtime object.[During execution]. It can only be used on the properties that an element support during execution. Use Object Spy tool to identify compatible properties who’s value can be fetched.We can use Regular expression too.

Example:

Browser("Google").Page("Google").WebEdit("q").set "AskUFT/QTP"
msgbox Browser("Google").Page("Google").WebEdit("q").getROProperty("Value")

It supports descriptive programming as well.

dim class_Name as String
class_Name=Browser("name:=Google").Page("title:=Google").WebEdit("name:=q").GetROProperty("nativeclass")

Name_of_variable[String]=<Fully Qualified DOM>.ObjectType<Object unique identifier>.getROProperty(“Property Name”)

Where we can use GetROProperty?

Mostly finding combo items,getting title,getting table size,We will be using this methos.
It is bit advanced than standard or text check point.

How To Retrieve Value from Webelement in UFT/QTP/UFT?

Scenerio is:-

1)We have an object as WebElement whose value is dynamically changing.For example,say i want to retrieve a policy number.When i added that object and retrieve with GETROPROPERTY,it is retrieving only one value which is added in the OR.For the next iteration it is throwing an error saying cannot find object.

In this scenerio, we use regular expression,but using that it didnt helped.What are the other way to solve this issue?Please help me regarding this.
 
If the value of the webelement changes then getROProperty sometimes do not work …
As you are capturing policy number. So i assume that it changes from policy to policy.
I dont know your application. I am assuming it is on Web and written on any of the web language.
I am taking an example of Gmail home page where the third space “Lots of space” is getting changed time to time.

How To Retrieve Value from Webelement in UFT/QTP/UFT?
How To Retrieve Value from Webelement in UFT/QTP/UFT?

So if you add this and try to use the function getROProperty ,then the problem you will face is like this only…

How To Retrieve Value from Webelement in UFT/QTP/UFT?
How To Retrieve Value from Webelement in UFT/QTP/UFT?

 
The alternative approaches are:

1.Please try to include additional properties inorder to make the webelement get identified as they could have added extra properties.Spy the object get the porperties for the extra properties
2.You can update the webelement from the application into the object repository and make sure class of the object is not changed.

How To Retrieve Value from Webelement in UFT/QTP/UFT?
How To Retrieve Value from Webelement in UFT/QTP/UFT?

Browser("Google").Page("Google").Sync
Browser("Google").Navigate http://www.google.co.in/
Browser("Google").Page("Google").Link("Gmail").Click
msgbox Browser("Google").Page("Gmail: Email from Google").WebElement("place").GetROProperty("innertext")
 
How To Retrieve Value from Webelement in UFT/QTP/UFT?
How To Retrieve Value from Webelement in UFT/QTP/UFT?

3. if the above approah does not give you the required result please try this…

Code:


Set childobjdes = Description.Create()
childobjdes("micclass").value="WebElement"
childobjdes("innerhtml").value=".*[A-Za-z0-9].*"
childobjdes("outertext").value =".*[A-Za-z0-9].*"
Set oWebElement = Browser("Google").Page("Gmail: Email from Google")
Set oStyle = oWebElement.Childobjects(childobjdes)
msgbox oStyle.count
For i=o to oStyle.count-1
msgbox i &"-" & oStyle(i).getROProperty("outertext")
Next

 

How To Retrieve Value from Webelement in UFT/QTP/UFT?
How To Retrieve Value from Webelement in UFT/QTP/UFT?

So you can exactly get the Element no and track your required no.

4. If all the above code does not give you the required result then you can actually go for this concept.
If you really see the webpage…this is a table structure. even UFT/QTP identifies those tables…the values of this space or policy number (for your case) is coming to cell of a table.

How To Retrieve Value from Webelement in UFT/QTP/UFT?
How To Retrieve Value from Webelement in UFT/QTP/UFT?

Now you need to add these tables to your OR. atleast the last table..
Code:


r= Browser("Gmail: Email from Google").Page("Gmail: Email from Google_2").WebTable("Less spamKeep unwanted").RowCount
c= Browser("Gmail: Email from Google").Page("Gmail: Email from Google_2").WebTable("Less spamKeep unwanted").ColumnCount(r) For i=1 to r 
For j=1 to c 
msgbox Browser("Gmail: Email from Google").Page("Gmail: Email from Google_2").WebTable("Less spamKeep unwanted").GetCellData(i,j)
Next 
Next
 
How To Retrieve Value from Webelement in UFT/QTP/UFT?
How To Retrieve Value from Webelement in UFT/QTP/UFT?

From the string you can find the policy number.

Hope this will help you.

 
GetTOProperty:
GetTOProperty can fetch values associated with test object residing in Object Repository.In simple words,this command or function returns the properties and values which UFT/QTP has learnt during recording of the flow. It stores all values in Object Repository. During run time, UFT/QTP tries to match the same values with application’s object to identify and perform operations..It reads all the value from object description.This can be used instead of standard check point to compare static values.

Syntax-
Variable_Name[of type String]=<Fully Qualified DOM>.ObjectType<Object unique identifier>.getTOProperty(“Property Name”)
Code:

dim class_Name as String
class_Name=Browser("Google").Page("Google").WebEdit("q").GetTOProperty("nativeclass")

It supports descriptive programming as well.

dim class_Name as String
class_Name=Browser("name:=Google").Page("title:=Google").WebEdit("name:=q").GetTOProperty("nativeclass")

 
During the use of GetTOProperty, many of us get the error called “Invalid procedure call or argument”. Most likely this error comes when we are trying to get property value which is not listed or learnt by UFT/QTP during recording time.Use Object Spy to get the correct set of value to be fetched from object property.All it fetches the basic static properties of the test object.
 
GetTOProperties:
This is one advanced command or method over GetTOProperty. GetTOProperty deals with a single value. GetTOProperties can fetch multiple properties from a test object.Again the basic is same. These values need to be stored in Object Repository.
Syntax-
Variable_Name[of type String array]=<Fully Qualified DOM>.ObjectType<Object unique identifier>.getTOProperties
Example:

dim object_properties as String array
dim name as String
dim alt as String
systemUtil.Run "iexplore.exe","http:/Google.com"
'Open google
Set ObjectEditBox=Browser("Google").Page("google").webEdit("q")
Set object_properties=ObjectEditBox.GetTOProperties
/This will fetch all TOProperties associated with editbox in the form of string array
for i=0 to object_properties-1
Name=object_properties(i).Name
alt=object_properties(i).alt
...
...
Next

 
SetTOProperty:
This method or command is used to modify a property value that UFT/QTP has learned during the record session and stored in Object Library. During recording UFT/QTP stores application properties and values in the Object repository and during a run session it creates a replica of the same.

Then, tries to match all the properties and its corresponding values. By SetTOProperty we change the replica version of those object’s property. So it is temporary and valid for each run session. After the run, UFT/QTP restores the original values.

In this case, the yellow box the original properties and values do not get affected. Mostly when there is no way to identify the object and no information available in Object Repository about the object we follow this approach to make UFT/QTP understand the new Object.
Example:
Say on a page there two links available for a table view.

  1. GoNext-Upon clicking this Application will produce next 10 records
  2. GoPrevious-Upon clicking Application will produce the previous 10 records.

So when we recorded, UFT/QTP learn about these two objects and stored in Object Repository. Now due to requirement change or any temporary change, it becomes “Next” and “Previous”. The working mechanism is the same. As this is a temporary change so we will not change the Object Repository ,rather we will change the way UFT/QTP identifies these object in such case SETTOProperty will be handy. For that, we will change the name property of these buttons.

Browser("ABC").Page("XYZ").webButton("GONext").SETTOProperty "name","Next"
Browser("ABC").Page("XYZ").webButton("GONext").Click
Browser("ABC").Page("XYZ").webButton("GOPrevious").SETTOProperty "name","Previous"
Browser("ABC").Page("XYZ").webButton("GOPrevious").Click

The only thing to remember before applying SETTOProperty is to disable the UFT/QTP’s Smart Identification mechanism to identify the Object. Secondly, it is done in an encapsulated manner hence the screen (Active) or the Object Repository. So they will remain unchanged.

One more scenario could be, when we need to work with multiple instances of the same page, all objects will be the same for this case. So while testing such instance we will be using SETTOProperty to identify them uniquely by providing separate names.
SetROProperty:
This is not available in UFT/QTP. Rather not required at all. During Runtime UFT/QTP is going to set the value anyway. This technique is important when UFT/QTP can not identify a text filed or some operation that UFT/QTP can not perform. We will adopt a javascript executor in such a case. Few UFT/QTP codes say it as SetROProperty. Let us discuss how:

set page=Browser("Google").Page("Google")
'setting the object for page
set googleTextBox=page.RunScript("document.getElementByName('q')(0);")
'Setting the object after finding in DOM
googleTextBox.value="TechTravelHub"

We can use getElementByID,getElementByXpath etc remember this is for fun and UFT/QTP does not have this method.

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.


Spread the love
  •  
    1
    Share
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

24 thoughts on “Learn UFT Step By Step Manner in a Fast Pace”

  1. Hi Animesh,

    This is kumar from chennai. I am a Newbie in QTP. I found your blog. I have following questions poke in my mind. Pls answer my questions:

    a) How to start QTP (Before i start what are things i should do)
    b) Could you pls give me 'Sample automation frame work' and how to create?
    c) Could you pls give me a any QTP use guide (If you have)


    Cheers
    Kumar

  2. After doing this vegetables and fruit focus upon landing
    world-wide-web site. Seaech Engine Optimization factor
    that actually is important ffor businesses in today’s times.
    In addition, they can also reduce the page ranking.

  3. Peoplle believe the latest versjon iis often the utmost.
    It is the only profession your own do not answer to anyone and so your oown boss.
    While trading live there is just not time to think.

  4. A website article can also enhance your website’s rank in all of the major web presence.
    So I think forr your seo wofk we end up being go wirh good
    satisfied. So, it goes without proclaiming that ‘title’ is crucial.

  5. I have read some just right stuff here. Certainly worth bookmarking for revisiting.
    I surprise how much attempt you put to create the sort of
    great informative web site.

  6. I’m gone to convey my little brother, that he should also pay a
    quick visit this weblog on regular basis to get updated from newest
    news.

  7. Reall are millions numerous free Swediish dating site that offer
    a lot of interesting individuals. When you’re
    not in cosmetic treatments have a swim your
    center’s bunch.

  8. I’m trying to change the entire background of my blogspot. I can get it on the left side, but the sidebar still remains at the ugly solid color. any help?.

  9. You actually make it seem so easy with your presentation but I find this topic to be actually something which I think I would never understand. It seems too complicated and extremely broad for me. I’m looking forward for your next post, I will try to get the hang of it.

  10. whoah this blog is wonderful i like reading your articles.
    Stay up the good work! You know, many people are looking round for this information, you could help them greatly.

  11. Don’t be rash with a decisions, but mae calculated risks.A
    stop loss is important, buut bee realistic and so tthat you
    cann wide suitable. The concept of binary options is undemanding.

  12. melinaconcepcion

    That is a good tip particularly to those new to the blogosphere.

    Simple but very accurate information… Appreciate your sharing this one.

    A must read post!

  13. Whoa! This blog looks exactly like my old one! It’s on a totally different subject but
    it has pretty much the same page layout and design. Superb choice of colors!

  14. candelariamccreary20

    It takes skill, determination, and doing its job a team to play football
    competently. It’s not really about playing the game but it’s
    more like really experiencing and enjoying the game.

    I actually attended anny of the while at school.

  15. Excellent post. I used to be checking constantly this blog and I am impressed! Extremely useful info particularly the last phase 🙂 I handle such info a lot. I used to be seeking this certain information for a long time. Thanks and best of luck.

  16. Heya i’m for the primary time here. I found this board and I find It truly useful & it helped
    me out a lot. I’m hoping to provide something again and aid others such as you helped
    me.

  17. Nice weblog right here! Also your website lots up fast!
    What web host are you the use of? Can I get your
    associate link to your host? I want my site loaded up as fast as yours lol

  18. whoah this weblog is excellent i like reading your posts. Stay up the good work! You recognize, many persons are searching round for this information, you could help them greatly.

  19. elisabeth_muller

    I know this website provides quality depending posts and other material, is
    there any other web page which gives these kinds of data in quality?

  20. Hey there, You’ve done an incredible job. I’ll definitely digg it and personally suggest to my friends. I am confident they will be benefited from this web site.

  21. This is when you will decide to understand a person can view the markets.
    You wjll have to system to make iit worse buying and selling resolutions.
    Again I ask why are you trying to kill me aand my friends.

  22. Just desire to say your article is as surprising.
    The clarity to your put up is just nice and
    that i can assume you’re an expert on this subject.
    Well together with your permission let me to clutch your
    feed to stay up to date with approaching post. Thank you one million and please carry on the enjoyable work.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top