Using Classes as Test Modules in QTP (Part I).
In this article, techniques of creating modular classes will be demonstrated. Usage of modular classes helps in keeping all methods and properties for a module intact, and if done correctly, this can simply maintenance greatly. This article serves as an introduction to Class usage in QTP. In the coming articles, we will discover advanced concepts in building highly stable and robust class modules.
Each modular class can contain one or more methods, which provide some functionality to a framework. Before adding the appropriate methods, we must create a modular class. In our demonstration, ‘clsLogin’ has been created, which as the name suggests, is a Login class.
Class clsLogin End Class
The goal of the class we created above is to Login to the Mercury Tours website. Let’s name our method ‘Login’ and include the steps that the method will perform:
Class clsLogin ' Login Public Function Login( sUserName, sPassword ) 'Page title Dim sTitle: sTitle = "Welcome: Mercury Tours" Login = False With Browser( "title:=" & sTitle ).Page( "title:=" & sTitle ) 'Set the userName .WebEdit( "name:=userName" ).Set sUserName 'Set the password .WebEdit( "name:=password" ).SetSecure sPassword 'Click SignIn .Image( "name:=login" ).Click End With 'If the correct Page appears: Step Passed If Browser( "title:=Find a Flight: Mercury Tours:" ).Exist( 5 ) Then Login = True End If End Function End Class
Let’s assume we have to check properties of the page banner, which is a part of our test-case. In reality, there may be multiple objects for which properties are being verified and they can be included within the same method. For our example though, we will verify property of a single object: page banner.
Class clsLogin ' CheckObjectProperties Public Function CheckObjectProperties 'Page title Dim sTitle: sTitle = "Welcome: Mercury Tours" CheckObjectProperties = False With Browser("title:=" & sTitle).Page("title:=" & sTitle) 'Check Page Banner If .Image("file name:=banner2.gif").GetROProperty("width") = 488 Then 'If the width equals the expected width, step passed CheckObjectProperties = True Reporter.ReportEvent micPass, "Banner", "Size Correct." Else Reporter.ReportEvent micFail, "Banner", "Size Incorrect." End If End With End Function ' Login Public Function Login( sUserName, sPassword ) Dim sTitle: sTitle = "Welcome: Mercury Tours" Login = False With Browser( "title:=" & sTitle ).Page( "title:=" & sTitle ) 'Set the userName .WebEdit( "name:=userName" ).Set sUserName 'Set the password .WebEdit( "name:=password" ).SetSecure sPassword 'Click SignIn .Image( "name:=login" ).Click End With Browser( "title:=" & sTitle ).Sync 'If the correct Page appears: Step Passed. If Browser( "title:=Find a Flight: Mercury Tours:" ).Exist( 5 ) Then Login = True End If End Function End Class
The 2 methods discussed above are quite common: we generally perform actions on objects and create checks to replace (manual) visual verifications. Now, before we can really perform the above 2 checks, we may also need to check whether we’re on the correct page. Let’s add another method for that:
Class clsLogin ' IsPageFound: Check if we're on the correct page Public Function IsPageFound 'Page title Dim sTitle: sTitle = "Welcome: Mercury Tours" IsPageFound = False With Browser( "title:=" & sTitle ).Page( "title:=" & sTitle ) If .Exist( 10 ) Then IsPageFound = True End If End With End Function ' CheckObjectProperties Public Function CheckObjectProperties Dim sTitle: sTitle = "Welcome: Mercury Tours" CheckObjectProperties = False With Browser( "title:=" & sTitle ).Page( "title:=" & sTitle ) 'Check Page Banner If .Image("file name:=banner2.gif").GetROProperty("width") = 488 Then CheckObjectProperties = True Reporter.ReportEvent micPass, "Banner", "Size Correct." Else Reporter.ReportEvent micFail, "Banner", "Size Incorrect." End If End With End Function ' Login Public Function Login( sUserName, sPassword ) Dim sTitle: sTitle = "Welcome: Mercury Tours" Login = False With Browser( "title:=" & sTitle ).Page( "title:=" & sTitle ) 'Set the userName .WebEdit( "name:=userName" ).Set sUserName 'Set the password .WebEdit( "name:=password" ).SetSecure sPassword 'Click SignIn .Image( "name:=login" ).Click End With 'If the correct Page appears: Step Passed. If Browser( "title:=Find a Flight: Mercury Tours:" ).Exist( 5 ) Then Login = True End If End Function End Class
If we observe the code above, the variable “sTitle” is present in each method. This is quite redundant. We can simply replace this with a readOnly property:
Class clsLogin ' Property sTitle Private Property Get sTitle 'ReadOnly Property sTitle = "Welcome: Mercury Tours" End Property ' IsPageFound Public Function IsPageFound IsPageFound = False With Browser( "title:=" & sTitle ).Page( "title:=" & sTitle ) If .Exist( 10 ) Then IsPageFound = True End If End With End Function ' CheckObjectProperties Public Function CheckObjectProperties CheckObjectProperties = False With Browser( "title:=" & sTitle ).Page( "title:=" & sTitle ) 'Check Page Banner If .Image("file name:=banner2.gif").GetROProperty("width") = 488 Then CheckObjectProperties = True Reporter.ReportEvent micPass, "Banner", "Size Correct." Else Reporter.ReportEvent micFail, "Banner", "Size Incorrect." End If End With End Function ' Login Public Function Login( sUserName, sPassword ) Login = False With Browser( "title:=" & sTitle ).Page( "title:=" & sTitle ) 'Set the userName .WebEdit( "name:=userName" ).Set sUserName 'Set the password .WebEdit( "name:=password" ).SetSecure sPassword 'Click SignIn .Image( "name:=login" ).Click End With 'If the correct Page appears: Step Passed. If Browser( "title:=Find a Flight: Mercury Tours:" ).Exist( 5 ) Then Login = True End If End Function End Class
Even though some methods of a class are crucial, they may only perform background operations. In our demonstration, IsPageFound and CheckObjectProperties are such methods. Both methods verify objects, and in the automation world, they can be very reasonable prerequisites to the main action, which is to Login to the application. In the demonstration below, IsPageFound and CheckObjectProperties have been marked as private. Both methods are included as a prerequisite to setting the userName and password for logging to the website. To reiterate, both IsPageFound and CheckObjectProperties can be made private methods of the class:
Class clsLogin ' IsPageFound: Private Function Private Function IsPageFound IsPageFound = False With Browser( "title:=" & sTitle ).Page( "title:=" & sTitle ) If .Exist( 10 ) Then IsPageFound = True End If End With End Function ' CheckObjectProperties: Private Function Private Function CheckObjectProperties CheckObjectProperties = False With Browser( "title:=" & sTitle ).Page( "title:=" & sTitle ) 'Check Page Banner If .Image( "file name:=banner2.gif" ).GetROProperty( "width" ) = 488 Then CheckObjectProperties = True Reporter.ReportEvent micPass, "Banner", "Size Correct." Else Reporter.ReportEvent micFail, "Banner", "Size Incorrect." End If End With End Function ' Login: Public Function Public Function Login( sUserName, sPassword ) Login = False If IsPageFound Then If CheckObjectProperties Then With Browser( "title:=" & sTitle ).Page( "title:=" & sTitle ) 'Set the userName .WebEdit( "name:=userName" ).Set sUserName 'Set the password .WebEdit( "name:=password" ).SetSecure sPassword 'Click SignIn .Image( "name:=login" ).Click End With End If End If 'If the Page with the title 'Find a Flight: Mercury Tours:' appears: Step Passed. If Browser( "title:=Find a Flight: Mercury Tours:" ).Exist( 5 ) Then Login = True End If End Function ' Property sTitle: Private Property Private Property Get sTitle sTitle = "Welcome: Mercury Tours" End Property End Class
If you notice the code above, you will see that both private methods have become a part of the Login method. They’re both prerequisites to logging in to the application. Only once both are True, will the code perform the code-action of the class. We can implement the class above using the following snippet:
Public Function Login( sUserName, sPassword ) Dim oAction: Set oAction = New clsLogin Login = oAction.Login( sUserName, sPassword ) End Function
If you would like to keep ‘IsPageFound’ and ‘CheckObjectProperties’ as public methods of the class, then you can even do this:
Public Function Login( sUserName, sPassword ) Dim oAction: Set oAction = New clsLogin Login = False With oAction If .IsPageFound Then If .CheckObjectProperties Then Login = .Login( sUserName, sPassword ) End If End If End With End Function
It is possible for a single function to do everything, but don’t you think its much easier to understand what each method of the class does with little effort? ‘IsPageFound’ simply checks if we’re on the correct page, ‘CheckObjectProperties’ checks if the object was loaded correctly, and ultimately, ‘Login’ performs to core-action by logging the user to the application. Moreover, all methods are grouped together in a class.
In practice, the entire test suite can be created on this principle with each module representing a core-functionality of the overall test. There are several ways to bind these modules together, and we must find an elegant solution for that as well. This is because, because of some major changes, we may need to completely remove a module, or even add one. Therefore, if done correctly, even such a big change can be implemented without much trouble. We will discuss such a technique in the next article in this series, which will be an advanced implementation of class usage in QTP.
I hope you guys find this article useful.

{ 50 comments… read them below or add one }
Hi Anshoo,
I had the following query with the usage of classes in qtp.
I understand that it provides support for modularity (i.e. a Login Module is converted into a class file with methods say to perform operations on objects + validations as required by the user).
How should i go ahead and use this class / incorporate the same in my framework which is something i am not able to get clarity on.
i.e. where is the object for this class being initialized / What is Class_Initialize and Class_Terminate events?
How exactly is the calling for this incorporated in the larger scheme of your framework.
Thanks a lot,
Hi Anshoo,
Today whatever I kno in QTP is just because of you.I can’t describe it in words(still unable to stop myself trying to describe)…..thanks a lot for that.I was pretty familiar to OOP far back in years,so have some unclear memories,thats y asking a silly question to u
“why we want to make sTitle = “Welcome: Mercury Tours” property private in this class what the practical advantage of that and wat the disadvantage if we make it public”
please give me a practical example of this instead of technical.
from above posted query i just wanted to refer that what actually is the use of encapsulation quality of class in terms of our routine test case script/automation development.
Thanks,
Piyush Kotiyal
Piyush,
It was just an example. If I wanted to use this variable outside of this class, I would have made it public. But since its use remains only for the functionality provided in the class, I decided to make it Private.
Hi Anshoo ,
I have doubt about Vbscript -OOPs .
What all OOPs concept are supported by VBscript?can you please illustrate with an example.
Did some one tried coping the class code in .vbs file and creating new instance of class in QTP and then calling the fuction like .VerifyUserId ..It is showing error that “Class name not defined”….
Can some one help on this? – Thanks
Hi Anshoo,
How are you? Its been long time over a year since I interacted with you last.I am at very interesting stage from QTP perspective.In most of the companies I worked so far they were using Data Driven framework but now demand is coming more and more in Keyword driven framework and I would like to learn and explore this framework with your help.I went to your site and saw your framework but that is implemented using class.I am not very much familiar with OO concept with regards to QTP vbscripting. Do you have any previous framework of keyword driven using regular vbscripting procedure then please share it with me.As I would like to start from regualr procedure with pure vbscripting without OO concept and may be a year down the line when I am too good with keyword approach I can move to implementing the OO concept.
I went through few articles over internet for keyword and found there are different sets of thing needs to be there in keyword framework:
FRAMEWORK STRUCTURE :
1.Function Library (is it vbs file)
2.Object Repository (how to load it in runtime and access when required)
3.Database (is it for read write?)
4.Application Scenario Files( is it in same excel sheet or seperate file than data sheet from where we reads data valus in data driven framework?)
5.Sequence File(what is this?)
6.Initialization VB Script(what is this?)
7.Driver Script(What is this, I guess QTP main script)
8.Test Case List File( is it in same excel sheet or seperate file than data sheet from where we reads data valus in data driven framework?)
Can you please explain how using these all we can develop the keyword driven framework. and without using class or object oriented programming.
Thanks
Vivek
Your are of great help man. Learnt many things from you. Waiting for the new article
I corrected the code and it is working now:
Class Login
Public Function VerifyUserId(userid)
VerifyUserId=False
If userid”" Then
VerifyUserId=True
End If
End Function
Public Function VerifyPassword(passwd)
VerifyPassword=False
If passwd”" Then
VerifyPassword=True
End If End Function
Public Function VerifyLogin(userid,passwd)
VerifyLogin=False
If VerifyUserId(userid) Then
If VerifyPassword(passwd) Then
Set oPage=Browser(“title:=Gmail.*”).Page(“title:=Gmail.*”)
oPage.WebEdit(“name:=Email”).Set(userid)
oPage.WebEdit(“name:=Passwd”).Set(passwd)
oPage.WebButton(“name:=Sign In”).click
VerifyLogin=True
End If
End If
End Function
‘Public Function VerifyLoginSuccess(userId)
‘ msgbox userId
‘ End Function
End Class
Public Function cLogin(username,password)
Set lg=New Login
VerifyLogin=lg.VerifyLogin(username,password)
End Function
Call cLogin(“vivek.kumar2005″,”anananana”)
Hi Anshoo ,after a long time coming back to your site to learn something new.I am planning to implement the OO concept in QTP scripting.I am not so good in OO but need to understand it soon.I went through advancedqtp website and also read other threads put by Meir-Bar Tal but could not grasp it properly.For a start just help me to understand what is wrong in my code.I am trying to write a class for Login to gmail account but getting error:
Class Login
Public Function VerifyUserId(userid)
VerifyUserId=False
If userid”" Then
‘checking here that userid is not empty then setting it to true
VerifyUserId=True
End If
End Function
Public Function VerifyPassword(passwd)
VerifyPassword=False
If passwd”" Then
‘checking here if password is not coming as empty and then setting it to true
VerifyPassword=True
End If End Function
Public Function VerifyLogin(userid,passwd)
VerifyLogin=False
‘ msgbox VerifyUserId
‘ msgbox VerifyPassword
If VerifyUserId Then ‘checking here is verifyuserid is true means not empty
If VerifyPassword Then ‘checking here if verifypassword is true means not empty
‘I am getting error in above code Wrong number of arguments or invalid property assignment:VerifyUserId
Set oPage=Browser(“title:=Gmail.*”).Page(“title:=Gmail.*”)
oPage.WebEdit(“name:=Email”).Set(userid)
oPage.WebEdit(“name:=Passwd”).Set(passwd)
oPage.WebButton(“name:=Sign In”).click
VerifyLogin=True
End If
End If
End Function
‘Public Function VerifyLoginSuccess(userId)
‘ msgbox userId
‘ End Function
End Class
Set lg=new Login
lg.VerifyUserId “vivek.kumar”
lg.VerifyPassword “xyzabcd”
lg.VerifyLogin “vivek.kumar”,”xyzabcd”
I went through your framework using keyword driven and OO concept but it is going well above my head for time being as I am not so comfortable with OO programming yet using VBscript.Still I want to understand how you implemented OO here on high level.
Do guide me.Looking forward for your reply.
Thanks
Vivek
On which line do you receive the error?
The following line:
should be:
Hi Anshoo,
Quote
“Usage of modular classes helps in keeping all methods and properties for a module intact, and if done correctly, this can simply maintenance greatly. ”
A very basic question, why to use VBS classes in QTP?
I don’t see any benefit, but the loss, QTP does not support intellisense those methods written inside class, so we need to remember their names, otherwise every time we have to dig inside the implementation to see function names and its signature.
on the other hand, QTP library (qfl) is nothing but a Class, and QTP IDE, support showing only public methods with intellisense, autocomplete and its signature, so i believe, writing methods directly inside qfl provide more value then implementing vbs classes.
Nothing to critic your efforts, but its QTP IDE, who is the culprit hear :)
Manish,
Class code is more managed as compared to having functions loosely stored in your function libraries. You can combine code from a single functionality into a single class, have a single entry point to access the class – you and your team will always know how to follow the code and how to maintain it, when required. Also remember, classes support encapsulation so you can create code in a way that the user does not need to know how the class performs an action. Instead, the user calls the public member that performs it.
Consider an application with 10 distinct functionality. Each functionality can be a class, with their methods laid out in each class. Create only the core methods of each functionality as public members, whereas all the internal code can be private, or hidden. Now, consider the public methods to only contain the flow or callbacks to these private methods. Each time you call a single public member to perform actions which are in reality handled by multiple methods of the class, but to the user, its only a single method that performs everything..
I agree about the lack of Intellisense, but that has been the only issue I have encountered with Classes. VBSEdit can be used to create components if it becomes too difficult to manage code and Intellisense becomes of high importance. Well, I still hope we’ll have a better IDE. With QTP 11, I do see a step in the right direction but we’re still quite far from our expectations :)
Hi Anshoo,
I have a question, can we store the actions code in the excel cells and have them loaded and executed in the QTP IDE??
By ‘Actions code in Excel’, do you mean the actual QTP code or the data that is present in the DataTable? If you mean the actual code, then a workaround is to have the code in library files and use these library files to drive the automation effort instead.
I have a question about using the class in QTP, I read from someone’s article he not suggeste to class in QTP, capability, maintainence, all bother us. So I am curious the advantages using class, will it has the function to extend the function from other classes I mean inherit from other classes?
Also I met one problem is if you write class in vbs and associate the vbs file with the QTP test, it can’t find the class, but after i copy the code to test or just executefile then it passed.
I just want to know the tips to using the class or the advantages of it. Thanks.
Hi Steven,
Can you please direct me to the article that is suggesting against the use of classes in QTP?
This is true to an extent, but I don’t really see this as a short-coming because there are very easy workarounds for this. Creating a reference to the class, or a sort of constructor can easily sort this, and we still get access to all the methods of the class that we create.
You will see a lot of examples that use classes on Relevant Codes, and that’s certainly for a good reason. The biggest benefit that classes can derive in terms of usage with QTP is that, all the methods of a functionality can be encapsulated within a single class. Therefore, you can create highly managed code – methods of a single functionality in a single place.
The key here is that we can encapsulate a lot of the functionality into a single class, and we reveal only what we want to, through Public Properties, Variables and Methods. Rest, we hide through the use of Private Properties, Variables and Methods. This is a very deep topic, and I would really like to suggest you to find resources on Google and read further, especially about Encapsulation, Polymorphism and Inheritance. However, one must note that VBScript only supports Encapsulation, but understanding the principles of Classes is quite important.
As I mentioned earlier that VBScript classes can be used as modules, thus, if I were to create a separate module for the Login page, everything can be encapsulated into a single working class that checks all the items, logs in the user and verifies if the login was successful. During maintenance, you would be required to look under a single place instead of browsing your library for related functions.
You can use each class to have methods that will:
1. Store objects (this will be a single method)
2. Perform Actions with the stored objects (this can be a single or multiple methods)
3. Perform validations (single or multiple methods)
4. Report and send results (if all the above are private, this can be public)
Therefore, if we have independent methods for each functionality within a single class, imagine how easy it will be to perform regular maintenance when GUI changes. You will be looking under a single class all the time. More over, since each method is independent of each other, a GUI change will only involve a change with the method that stores all the objects. All the other methods will stay intact.
I don’t want to lengthen this discussion and will wait for your response before going deeper in this topic :)
Great Work Anshoo!!!
Thanks Devendra :)
Hi Anshoo
Again nice work. You just implement the OOP’s concept. In practical. Here I am getting the things as I want to learn. Waiting for your new post.
Thanks
Thanks Amit :)
Thank you Anshoo! thnx a lot :)
:)
Thank you Anshoo for your wonderful explanation.
Is there any difference between
1. Private sTitle= “Welcome: Mercury Tours” and
2.Private Property Get sTitle ‘ReadOnly Property
sTitle = “Welcome: Mercury Tours”
End Property
In above Both cases sTitle cannot be accessed from outside the class.
Kindly clear my doubt…
Bibek,
The property in its ‘Get’ or Read-Only form cannot be altered. It can only be read, not written over. Therefore, the reason why I use Read-Only properties.
The usage in #1 is illegal. It will always throw an error.
That’s true… but then, it will be a variable which will be allowed to be altered from within the class. The property Get block will always prevent that.
Anshoo! Rocking techniques as always…Really nice concept.
I have one question:”If we observe the code above, the variable “sTitle” is present in each method. This is quite redundant. We can simply replace this with a readOnly property:”
What is the actual use of GET/SET property and what benefits the above code/script is getting.. i.e after defining sTitle as readonly?
Expecting a lot :)
Thank you, Bibek.
Defining sTitle as read-only means, there is no way the Title of the page can be changed through code, especially through a human error. ReadOnly properties, that is, properties without the Let component enable developers to create region specific variables that can only be accessed as read-only components, an not over-written by any other methods or class callers.
Get -> Output Only
Let -> Input Only
If you would like the outside world, or the class methods to be able to change that property, you can include a Let component, which will take an input to the Property-Block, and retrieve that input from its Get component.
Hi Anshoo,
i have search the so many forum but not able to find the complete information . i am vary happy and giving the so many thanks to you for providing the such type of information.
Raj kumar
Thank you :)
Hello Anshoo, I am glad to found that article about OO programming in vbscript for testing purposes. I am supporter of such attitude. Great work! You put lot of you time for t hat site – thanks for that!
Thank you, Piotr. I’m glad you found this technique useful. :)
Excellent job done!
I was looking for OO approach to do automation. This above code snippet is realy helpful.
Thanks for sharing this we all reader.
Great, Amrit! Glad it helped! :)
Anshoo.. Excellent!! I Appreciate for this great job :)
Thank you, Sam!
Greet work
Thank you! :)
Hi Anshoo
Nice work done .. :)
Thanks, Pooja! :)
Hello Iris,
I’m glad you found this article useful.
To be able to answer your question accurately, could you please provide a little more detail for your query? Thanks.
-Anshoo
The article is good which indicate OO sense of automation
As far as i concern, the reuse package of automation is prefer (Except the UI factor)
let me know what is your advice on this aspect
Suni, I’m glad you found this useful.
Cheers- Anshoo
Hi Anshoo,
I like all ur articles on siebel and am very excited after seeing the implementation of OO concept in Automation. I am tring to implement this in siebel Automation.Thanks for ur wonderful Knowledge Trasfer
@Hari: Thanks. I am glad you found this post useful. Your code above is why more and more people have started using pure OO principles even in Test Automation. You will see Class usage across many QTP forums, and its for the very reason that you mentioned in your post. There are plenty of articles on AdvancedQTP that you can refer to, and I will be writing a follow-up of this article demonstrating advanced concepts in Classes as well which should be out in a few days.
@Steve: Thanks! To answer your question about the above 2 issues:
A “type mismatch error” generally occurs when a function/sub is called before its definition is being executed. In other words, if a function is not loaded and yet you try to call it – that’s an error.
“Object not found in Object Repository” is quite common and generally occurs when you are trying to perform an event on an object that has an OR style definition, and that definition is not found in the Object Repository.
Example:
Browser("Google").Page("Google").WebEdit("q").Set "Google Search"If both Browser and Page objects are added to the repository, but the WebEdit isn’t, you will get the above error when you execute that line of code.
PS. I will surely be contacting you soon for advice :)
Hi Anshoo,
i have been thinking of using this approach from a long time(OO). But as a junior most member of the team it is difficult to get it implemented and there is a common misconception that OO is a very complicated thing.
But any how
Admin.login()
Admin.VerifyAlerts()
always sounds better than
login()
VerifyAlerts()
Any how, i will keep on trying to convince them.and may be if there are more articles like these people may start using OO.
So thumbs up!
Greetings!
This is fascinating and useful information! As for a simple QTP question, if I get a “Type Mismatch” or “Object not found in Object Repository” (when the object is indeed located in the OR), what is the best way to debug these types of errors?
In return for this answer, please contact me with any photography-related questions!
Thank you,
Steve
ss.mba@verizon.net
Thanks for the quick reply.
As the article that against using the class I am not able to find the source but I have the text that I copy to my blog, you can see the detail below.
–start
–end
So I think the author concern about the ability of the newbie and also the support from the IDE. Also I am not the advanced user I just part time do the QTP and my major job is to test PL/SQL currently. But my next direction is I am trying to convert to one QTP automation tester. Because I am more interested in that and can find the emotions here.
Absolutely. I wouldn’t recommend using them – its definitely a matter of preference, experience with programming languages and most of all, experience with QTP. That statement is logical, but I also feel that there is a little bit of nitpicking involved.
Steven, I would definitely recommend you to learn QTP and become very comfortable with it. Having good experience with the tool itself is very important. It is a very interesting field, and there are hundreds of people ready to help you.
Good luck :)
Piyush: This discussion boils down to Object Oriented vs Procedural programming, which is quite a broad topic. I would like to share this link with you: http://www.virtuosimedia.com/dev/php/procedural-vs-object-oriented-programming-oop. Its a pretty good read.
{ 1 trackback }