RSS Feed

Monthly Archives: April 2015

How to Translate Manual Test Cases into Automation Scripts? – A Step by Step Guide with Example

How to design an automation test case or script?

Automation always follows manual testing. Typically, one or more rounds of manual testing already would be performed on the AUT. This implies that manual test cases already exist and have been executed at least once.

For example, assume the following is your manual test case. It is a simple logging on to Gmail.com site. Now, this looks simple enough, isn’t it? How does this become an automation script? (click on image to enlarge)

Manual-Test-case

How to translate this manual test case into an automation script?

Automation-testing-process

The following are the guidelines we are going to follow to achieve the translation into an automation script:

#1: State of the AUT: The column precondition is nothing but a particular state of the background to be set for a certain step to be executed. This is especially important in two scenarios:

To begin the test:  In this case, we need the browser available and launched. (The username and password availability will be dealt with in a little while).  Now, how to write the same thing in the automation world? Consider QTP. You have an option to either launch the browser using programmatic statements or you can use the ‘record and run setting’ dialog to set the properties. Setting these properties correctly is very crucial. Often this is the reason why a particular piece of code will work in a machine and won’t work in the others.

To execute a certain step: For step2 to be performed we need step 1 to be done and complete. To do so manually, we can just wait until the step execution is done and the page gets loaded fully.  Use the sync or wait statements in your automation script to wait until the desire state comes true.

Note:  When you are running the same code for multiple sets of data, you would want to make sure that you are returning the AUT to the state that it should be before the next iteration start.

#2: Test Steps:

We can categorize the manual test steps into 3 categories:

Data entry – Data entry steps are where you are entering some information as an input to your AUT.
Change of AUT state steps – these steps are the ones that will cause a change to happen to your AUT. It might include going a new page, a certain field being visible, an edit box being editable etc.
Combination – as the name implies, this is combination of both of the above types. Take the case of a checkbox, when turned on will make a certain field active. In that case, you are entering the value “True” for the checkbox field and it also results in a state of your AUT.
In the above test case, only the type 1 and 2 steps exist.

Type 1: test steps 2 & 3
Type 2: Test steps 1 & 4
The pre-requisite to creating an automation script using any tool is to spend some time analyzing the tool as well as AUT. Try to see how both of them interact with each other. For example: QTP has 3 recording ways and each one works a different way. If you know how it identifies objects, you would know which one to use and use it better.  If you have a web app where QTP can identify the objects easily, you can use the normal mode. If not you might have to use the analog or low level methods.

Automation steps:

Data entry steps are not very different in the automation and manual methods. All you do is enter the data. The way you reference the field is different. Since it will be machine performing the steps, we just have to make sure we refer to the fields in the AUT in a way that the tool understands. That means, you have to use its logical name as used in the code.

For Change of AUT /Combination steps in a manual scenario, you perform the action (clicking or checking or entering) and verifying the change at one go. But in an automation scenario that is not possible. So we have to make sure we add steps for action and validation/verification.

Comments for readability.

Debugging statements – these are especially important which you are creating and testing the test itself. Try to use message boxes frequently to output various values at various stages of test execution. This will give you a visibility into the test like nothing else would.

Output statements – to write to results or any other external place like a notepad or excel sheet.

#3:  Verification and Validation

Without verification and validation the intent of testing is lost. Typically you will have to use a checkpoint (does not necessarily mean the inbuilt ones). So you will have to use a lot of conditional statements and also loop statements to build the logic.

An important thing to consider is- the attribute based on which you are basing your v&V should not be ambiguous. For example, for successful login, look for the inbox page display not for the number of new mails, because that is not a constant value.

So you have to pick something that is true every time a set of operations happen – without fail.

#4: Test Data

The following are some of the questions that you might consider answering for your test data requirements:

1. Where to place it?
2. To hard code or not?
3. Security concerns?
4. Reusability concerns?
When you look back at the manual test script, you will notice that having the test data, the username and password available is one of the preconditions to even begin the test.

#5: Results

For a manual test case, you can put the result of each step in the “actual result” column. An automation tool’s result file contains the result of each step when executed.

Automation tools these days have very robust reporting features. However, you might still need to tailor the test results. So include the steps to write frequently to the result file so that you will know exactly what went on while the execution was happening. If the tool you are using does not support writing to the result file it generates, it is a good idea to have at least an excel sheet or notepad associated with each test to put in comments about the execution status as you go.

#6: Post Operations

Once you are done with testing it need not be explicitly mentioned in your manual test case to close the browser or close the AUT etc. As a tester you would do it diligently. In the case of automation test case, you can include these steps in your script. Clean up – is what I call these activities. Kill all the connections you created. Close all the apps. Release the memory.

Manual-to-automation-testing

Let us walk through each step:
Step 1: precondition. We are launching the IE with the Gmail.com URL programmatically.

Step 2 & 7: Sync statement. As we discussed above, these are important to making sure the AUT comes to the desired state before the next step execution follows.

Step 3 & 4: Data entry. All the data is hard coded into the script. Although not advisable, it’s a start.

Step 5: Change of AUT step. Step 5 includes clicking on Sign In button. You will not need a V&V when this statement gets executed. That is because, there is a subsequent statement and if that can run; it means the one before it has been successful. But if you are extra diligent, you can include one here.

Step 6 & 8: comments

Step 9 & 11: Conditional statement. V&V/Checkpoint. We are trying to see if the login has been successful by checking if there is an inbox link in the resulting page. If you note carefully, link with inner text, “inbox.*” is looked for. So irrespective of any number of new emails(which is variable) received, if you have an inbox link(which is always a constant) available, that means the checkpoint passed.

Step 10: Message box. For visibility

Step 12 & 13:  These are the cleanup activities. You are signing out from the account and closing the browser.

Conclusion : 

So, you see how easily an automation script unfolds when you have a well written manual script and a set of basic guidelines to follow. Since this is not an article concerning frameworks, I stayed clear from functions, reusability factors, parameterization etc. Test script being the fundamental building block, it is easy to improvise on a script when you have the basics right.

Are there any other factors you consider, another method you find easier or any guideline that you find hard to follow? Please let me know your feedback in the comments.

Advertisements

QTP Web Scripts For Beginner

1) Count all opened Browsers on desktop and close them all?

Set oDesc = Description.Create()
oDesc(“micclass”).Value = “Browser”
Set Browsers =Desktop.ChildObjects (oDesc)
NumberofBrowsers = Browsers.Count()
Reporter.ReportEvent 2,”Res”,”Number of Browsers are: “&NumberOfBrowsers
For Counter=0 to NumberofBrowsers-1
Browsers(Counter).Close
Next

2) Count, how many links available in Mercury Tours Home Page.

Set oDesc = Description.Create()
oDesc(“micclass”).Value = “Link”
Set Lists = Browser(“Welcome: Mercury”).Page(“Welcome: Mercury”).ChildObjects (oDesc)
NumberOfLinks = Lists.Count()
Reporter.ReportEvent 2,”Res”,”Number of Links are: “&NumberOfLinks

3) Verify whether the ‘Gmail’ link available or not on Google Homepage

Option explicit
Dim oLink, Links, TotLinks, i, myLink
Set oLink = description.Create
oLink(“micclass”).value = “Link”
SystemUtil.Run “D:\Program Files\Internet Explorer\IEXPLORE.EXE”
set Links = Browser(“name:=Google”).page(“title:=Google”).ChildObjects(oLink)
TotLinks = Links.count
For i =0 to TotLinks-1
myLink = Links(i).getroproperty(“innertext”)
If mylink = “Gmail” Then
reporter.ReportEvent 0,”res”,”Link Gmail available”
End If
Next
4) Count number of Links, Edit Boxes available on Google Homepage?

Dim oLink
Set oLink=description.Create
Set oEdit=description.Create
oLink(“micclass”).value=”Link”
oEdit(“micclass”).value=”WebEdit”
Set Links=browser(“name:=Google”).page(“title:=Google”).ChildObjects(oLink)
Set EditBoxes=browser(“name:=Google”).page(“title:=Google”).ChildObjects(oEdit)
TotLinks= Links.count
TotEditBoxes=EditBoxes.count
msgbox TotLinks
msgbox TotEditBoxes
Reporter.ReportEvent 0,”Result”,”Total Links are: “&TotLinks&”Total edit Boxes are: “&TotEditBoxes

5) Count how many links available in a Web Page(any web page, using Regular Expressions)

Dim oLink,Links, TotLinks
Set oLink=Description.Create
oLink(“micclass”).value=”Link”
Set Links=Browser(“title:=.*”).page(“title:=.*”).ChildObjects(oLink)
TotLinks=Links.count
msgbox TotLinks
Reporter.ReportEvent 2,”Res”,”Total Links are: “&TotLinks

6) Verify Cost in jjperfumes.com
‘Test Flow
‘i) Launch jjperfumes.com
‘ii) Select a product and enter some quantity
‘iii) select Add to Cart, capture Unit price, Quantity and Cost
‘iV) Remove $ symbols and compare
‘———————————- —–

SystemUtil.Run “C:\Program Files\Internet Explorer\iexplore.exe”,””,”C:\Documents and Settings\gcr.GCRC-9A12FBD3D9″,”open”
Browser(“Google”).Page(“Google”).Sync
Browser(“Google”).Navigate “http://www.jjperfumes.com/”

Browser(“Google”).Page(“JJ Perfumes-Discount perfume”).Image(“thumb_1845_WLINP50PSW”).Click
Browser(“Google”).Page(“JJ Perfumes-Discount perfume_2”).WebEdit(“quantity”).Set “4”
Browser(“Google”).Page(“JJ Perfumes-Discount perfume_2”).WebButton(“Add To Cart”).Click

Unit_Price = Browser(“Google”).Page(“JJ Perfumes-Discount perfume_3”).WebElement(“[Remove]”).GetROProperty(“innertext”)
Qty = Browser(“Google”).Page(“JJ Perfumes-Discount perfume_3”).WebEdit(“quantity[]”).GetROProperty(“value”)
Cost = Browser(“Google”).Page(“JJ Perfumes-Discount perfume_3”).WebElement(“[Remove]_2”).GetROProperty(“innertext”)

Qty=Cint(Qty)
Unit_Price=Cdbl (Mid (Unit_Price,3))
Cost=Cdbl (Mid (Cost, 3))
‘Msgbox Unit_Price: Msgbox Qty: Msgbox Cost

If Cost=Qty * Unit_Price Then
Reporter.ReportEvent micPass,”Res”,”Cost is Correct”
Else
Reporter.ReportEvent micFail,”Res”,”Cost is InCorrect”
End If
Function To Create HTML Report
Dim StartTime,stTime, enTime
Dim fso, ts,intCnt, intPass,intFail
intPass=0
intFail=0
Const ForWriting = 2
Function OpenFile (strFileName)
StartTime = Timer
stTime = Time
Set fso = CreateObject(“Scripting.FileSystemObject”)
Set ts = fso.OpenTextFile(strFileName,2)
‘OpenFile = strFileURL
CreateHeader
End Function

*****************************

Function To Close File

Dim objIE,strFileURL
Function CloseFile ( strFileURL,strEnv )
Footer(strEnv)
ts.close()
Set objIE = CreateObject(“InternetExplorer.Application”)
objIE.visible = True
objIE.Navigate strFileURL
wait(5)
Set objIE=nothing
End Function

***********************

Function to Clear Cookies

Function ClearCookies()
SystemUtil.Run “iexplore.exe”
WebUtil.DeleteCookies
Set objBrowser=Description.Create
objBrowser(“micclass”).value=”Browser”
Set objBCount = Desktop.ChildObjects(objBrowser)
intBrowserCount = objBCount.Count
strHwnd=Browser(“creationtime:=” & intBrowserCount).GetROProperty(“hwnd”)
SystemUtil.CloseProcessByHwnd(strHwnd)
End Function

***********************

Function to send Email

Function SendMail()
If k=0 Then
‘Nothing
Else
msgsub = ” Geo_PostalCode pattern searchTest Results:” &vbcrLf &”One or more of the Test Cases Failed.” &vbcrLf &”See attachment for details.”
End If
Set objConf = CreateObject(“CDO.Configuration”)
cdoSendUsingPort=2
sMailServerName=”smtp.phx.move.com”
cdoAnonymous=cdoNONE
objConf.fields.item(“http://schemas.microsoft.com/cdo/configuration/sendusing”) = cdoSendUsingPort
objConf.fields.item(“http://schemas.microsoft.com/cdo/configuration/smtpserver”) = sMailServerName
objConf.fields.item(“http://schemas.microsoft.com/cdo/configuration/smtpauthenticate”) = cdoAnonymous ‘cdoBasic
objConf.fields.Item(“http://schemas.microsoft.com/cdo/configuration/smtpusessl”) = False
objConf.fields.Item(“http://schemas.microsoft.com/cdo/configuration/smtpserverport”) = 25
‘objConf.fields.item(“http://schemas.microsoft.com/cdo/configuration/sendusername”) = “corp\ NRaoJ ”
‘objConf.fields.item(“http://schemas.microsoft.com/cdo/configuration/sendpassword”) = “123K!r45”
objConf.fields.Item(“http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout”) = 60
objConf.fields.Update
Set objMsg = CreateObject(“CDO.Message”)
objMsg.Configuration = objConf
objMsg.to = “gcreddy@gmail.com”
objMsg.From = “gcreddy@gmail.com”
objMsg.Subject = “~Geo_PostalCode pattern search”
objMsg.TextBody =msgsub
doc=strFilepath
objMsg.AddAttachment(doc)
objMsg.Send
Set objMsg = Nothing
NewMail = True
End Function
***********************

Function to create append excel

Function LogFile
Set objExcel=CreateObject(“Excel.Application”)
objExcel.visible=False
objExcel.workbooks.open(strFilePath)
r=1
Do Until len(objExcel.cells(r,1))=0
r=r+1
Loop
objExcel.cells(r,1).value=”Step Name”
objExcel.cells(r,2).value=”Step Description”
objExcel.cells(r,3).value=”Test Results”
objExcel.DisplayAlerts = False
objExcel.Save
objExcel.Quit
Set objExcel = Nothing
End Function

***********************
Function to get the Application Environment on which the script is running

Function GetEnv()
Set fso=Createobject(“Scripting.FileSystemObject”)
sFile=”C:\WINDOWS\system32\drivers\etc\hosts”
Set MyFile=fso.OpenTextFile(sFile,1, True)
Do
sEnv=MyFile.ReadLine
If instr(sEnv,”PRODUCTION”)>0 Then
GetEnv=”Production”
Exit do
Elseif instr(sEnv,”Staging”)>0 Then
GetEnv=”Staging”
Exit do
Elseif instr(sEnv,”QA MAINTENANCE”)>0 Then
GetEnv=”QAM”
Exit do
Elseif instr(sEnv,”qap.”)>0 Then
GetEnv=”qap”
Exit do
End If
Loop While MyFile.AtEndOfStream=False
End Function

***********************

Function To Create HTML Report
Dim StartTime,stTime, enTime
Dim fso, ts,intCnt, intPass,intFail
intPass=0
intFail=0
Const ForWriting = 2
Function OpenFile (strFileName)
StartTime = Timer
stTime = Time
Set fso = CreateObject(“Scripting.FileSystemObject”)
Set ts = fso.OpenTextFile(strFileName,2)
‘OpenFile = strFileURL
CreateHeader
End Function

QTP Custom image capturing script

You should start with following code

RegisterUserFunc “Page”, “CaptureScreenshot”, “CaptureScreenshot”
RegisterUserFunc “Browser”, “CaptureScreenshot”, “CaptureScreenshot”
RegisterUserFunc “Frame”, “CaptureScreenshot”, “CaptureScreenshot”
RegisterUserFunc “Dialog”, “CaptureScreenshot”, “CaptureScreenshot”
RegisterUserFunc “swfWindow”, “CaptureScreenshot”, “CaptureScreenshot”

use the following line where you want take screenshot or snapshot

Browser(“micclass:=Browser”).Page(“micclass:=Page”).CaptureScreenshot micPass, “<h4 align = “”Center””>Page SuccessFully Displayed</h4>”

The below code is a library file. Add the library file to the script

Public Sub CaptureScreenshot( ByRef Sender, ByVal micStatus, ByVal descriptionStr )
Dim dateTimeNow, fileNameStr, divDesc, caption
Dim dicMetaDescription, qtp
dateTimeNow = DotNetFactory.CreateInstance( “System.DateTime” ).Now.ToString( “ddMMyyHHmmss” )
fileNameStr = Reporter.ReportPath & “\” & dateTimeNow & “.png”
Set qtp = CreateObject( “QuickTest.Application” )
qtp.Visible = False
Wait 0, 500
If IsObject( sender ) Then
Sender.CaptureBitmap fileNameStr, True
caption = Sender.ToString & ” – Capture Bitmap”
Else
Desktop.CaptureBitmap fileNameStr, True
caption = “Desktop – Capture Bitmap”
End If
qtp.Visible = True
divDesc = “<table align=’center’ border=’5′ cellpadding=’1′ cellspacing=’1′ width=’100%’ title='” & fileNameStr & “‘ frame=’hsides’>” & _
“<caption>” & caption & “</caption>” & _
“<thead><tr><th>Application Exception Description</th></tr></thead>” & _
“<tfoot><tr><td align=’center’><img border=’2px’ src='” & fileNameStr & “‘ /></td></tr></tfoot>” & _
“<tbody><tr><td>” & descriptionStr & “</td></tr></tbody></table>”
Set dicMetaDescription = CreateObject( “Scripting.Dictionary” )
dicMetaDescription( “Status” ) = micStatus
dicMetaDescription( “PlainTextNodeName” ) = “ApplicationException”
dicMetaDescription( “StepHtmlInfo” ) = “<DIV align=center>” & divDesc & “</DIV>”
dicMetaDescription( “DllIconIndex” ) = 205
dicMetaDescription( “DllIconSelIndex” ) = 205
dicMetaDescription( “DllPAth” ) = EnVironment( “ProductDir” ) & “\bin\ContextManager.dll”
Call Reporter.LogEvent( “User”, dicMetaDescription, Reporter.GetContext )
dicMetaDescription(“User”) = EnVironment (“dicMetaDescription”)
dicM
End Sub

To get HTML report there is registry modification of qtp registries.

HKEY_LOCAL_MACHINE\SOFTWARE\Mercury Interactive\QuickTest Professional\Logger\Media\Log Change the active DWORD from 0 to 1. What ever is running in qtp script it will generate HTML report at the time of result and it will save it folder name LOG in Results folder

For Eg: F:\Automation Projects\——–\Res1\Log

NOTE : You can use the above script capturing screenshots if there is an error while running QTP Test Runs

QTP scripts examples for beginner

QTP scripts examples for beginner

Hi friends, This post is useful for fresher who are looking for QTP scripts examples so that they can understand the qtp automation better. If you are advance users than just go through this blog you will get lots of advance QTP VB scripts examples which will be useful for your automation project.

I have listed here two QTP scripts examples specially for fresher, one is related to webpage and other is related to simple GUI (Graphical user interface).

Sample QTP script 1:

SystemUtil.Run “notepad”,””,””,””
Window(“Notepad”).WinEditor(“Edit”).Type “yes”
Window(“Notepad”).WinEditor(“Edit”).Type micCtrlDwn + “s” + micCtrlUp
Window(“Notepad”).Dialog(“Save As”).WinEdit(“File name:”).Set “test”
Window(“Notepad”).Dialog(“Save As”).WinButton(“Save”).Click

Above sample script will open notepad type yes and save as named test at default location.

Note: This is just sample script, This will not work if you just copy and paste it to QTP. You have to first record it. Please Refer to know how to record above script : Getting started to QTP.

Sample QTP script 2:

SystemUtil.Run “http://google.com/“,””,””,””Browser(“Google”).Page(“Google”).WebEdit(“q”).Set “mba” Browser(“Google”).Page(“Google”).WebEdit(“q”).SubmitBrowser(“Google”).Page(“mba – Google Search”).SyncBrowser(“Google”).Close

Above sample script will open google.com and type mba in search box and close it.

Note: This is just sample script, This will not work if you just copy and paste it to QTP. You have to first record it. When you record any webpage its objects will be automatically stored to object repository. Please Refer to know how to record above script : Learn to Automate Webpage.
Visit here to get detail knowledge of QTP object Repository and Learn QTP Step by Step.
Keep visiting this blog, I will share some more advance QTP VB script examples. You are always welcome to give feedback that will improve my blog. I am always trying to give 100% perfect knowledge about QTP.

If you like this article, You can subscribe through mail.

QTP – Create a Simple Script without Recording

If the QTP’s recording engine is used to record a test scenario, then the script will have following issues:

Script will have hardcoded values
1. No proper naming convention
2. No modularity
3. No reusability
4. Maintenance is difficult
5. Difficult to accommodate frequent changes
6. Difficult to debug
How to overcome these problems?

Simple!!

Create your own script… do not use recorded script..

Let us create a simple hand coded script and then compare with the recorded one.

Recorded Script:

SystemUtil.Run “C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe”,””,”C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\”,”open”
Dialog(“Login”).WinEdit(“Agent Name:”).Set “admin”
Dialog(“Login”).WinEdit(“Agent Name:”).Type micTab
Dialog(“Login”).WinEdit(“Password:”).SetSecure “4eece6099d2b0bb2783b322b99abefc8f36ecf1c”
Dialog(“Login”).WinButton(“OK”).Click
Window(“Flight Reservation”).WinMenu(“Menu”).Select “File;Exit”

Script created without Recording:

‘Script – “Login and Logout” the Flight application
‘Username and Password are parameterized through DataTable
‘ Purpose – Demonstrates creating script without Recording Engine
‘Author – Thomas Vinod
‘Copyrights – All rights reserved

Dim uname, pwd
uname=DataTable.Value(“username”,”Global”)
pwd=DataTable.Value(“password”,”Global”)
SystemUtil.Run “C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe”
Dialog(“LoginDialog”).WinEdit(“AgentNameEdit”).Set(uname)
Dialog(“LoginDialog”).WinEdit(“PasswordEdit”).SetSecure Crypt.Encrypt(pwd)
Dialog(“LoginDialog”).WinButton(“OKBtn”).Click
Window(“FlightReservationWin”).WinMenu(“Menu”).Select “File;Exit”

Compare both the scripts:

Recorded script:

1. No proper naming convention
2. Test data is hardcoded

Script without recording:

1. Proper naming convention is used
2. Test data is parameterized
3. Easy maintenance

How to create a script without recording?

1. Create local repository / shared repository with proper logical name for each object (http://goo.gl/CFjj9/http://goo.gl/aQnNR)
2. Parameterize Test Data from data table (http://goo.gl/LOfHX)
3. Start typing the code… Dialog( –> press open bracket that shows the number objects available, then just select the required object
4. Use appropriate actions such as Click, Set, Type, etc

Run both the scripts and view the results. It is even easy to analyze the results if proper naming convention is used in the object repository. If there is any need to execute the same test scenario for multiple iterations, we need to add just some more rows in the data table, but there is no need to copy and paste the same recorded script again and again.

I hope this gives a fair idea of how to create a simple hand coded script in QuickTest Professional (QTP).

%d bloggers like this: