How to get system date in QTP

Code for getting system date is given in below example.

print date.

Here date is the built in vbscript function which returns system date in QTP

Real life Scenarios where you will be using this function is ->
  1. Suppose you are working on the trading application. You need to calculate the settlement date.If you execute the order today, Trade date is today's date so you can use date function in this case.
  2. Date function is also useful to store your QTP results in date wise folders. This is used while designing the QTP framework.

How to get system time in QTP

code for getting system time is given in below example.


print time

here time is built in vbscript function which returns system time in QTP.

How to convert date format in qtp

Example -


Below code will convert date format in QTP. To verify the dates, you must have actual and expected dates in same format.

So you must convert the dates in a typical format like ddmmyyyy or mmddyyyy etc.

Below function will get the date in mm/dd/yyyy format.
Call Getdate("T") - will return todays date
Call Getdate("T+1") - will return tommorrow's date
Call Getdate("T-1") - Will return previous day's date.
you can calculate any future or past date with this example.


Function GetDate(byval curvalue)
   If  ucase(curvalue) = "T" Then
        curvalue = curvalue & "+0"
   End If


If  instr(1,curvalue,"+") > 0  Then
                        arrdate = split(curvalue,"+")
                       retDate = dateadd("d",arrdate(1),now)
                   
                   
                       strmonth = month(cdate(retDate))
                       strday = day(cdate(retDate))
                       stryear = year(cdate(retDate))
                   
                       If len(strmonth) = 1 Then
                            strmonth = "0" & strmonth
                       End If
                   
                       If len(strday) = 1 Then
                            strday = "0" & strday
                       End If
Else

                        arrdate = split(curvalue,"-")
                        curDate = - cint(arrdate(1))
                       retDate = dateadd("d",curDate,now)
                   
                   
                       strmonth = month(cdate(retDate))
                       strday = day(cdate(retDate))
                       stryear = year(cdate(retDate))
                   
                       If len(strmonth) = 1 Then
                            strmonth = "0" & strmonth
                       End If
                   
                       If len(strday) = 1 Then
                            strday = "0" & strday
                       End If


End If
  
    If Ucase(strParameter1) = "YYYY-MM-DD" Then
        GetDate  = stryear & "-" & strmonth & "-" & strday
    Else
        GetDate  = strmonth & "/" & strday & "/" & stryear
    End If
   
   

End Function

How to change a date format like mm dd yyyy in QTP

Example -


Below code will verify date format in QTP. To verify the dates, you must have actual and expected dates in same format.

So you must convert the dates in a typical format like ddmmyyyy or mmddyyyy etc.
To get date in any other format you need to modify last part of function.

Below function will get the date in mm/dd/yyyy format.
Call Getdate("T") - will return todays date
Call Getdate("T+1") - will return tommorrow's date
Call Getdate("T-1") - Will return previous day's date.
You can calculate any future or past date with this example.


Function GetDate(byval curvalue)
   If  ucase(curvalue) = "T" Then
        curvalue = curvalue & "+0"
   End If


If  instr(1,curvalue,"+") > 0  Then
                        arrdate = split(curvalue,"+")
                       retDate = dateadd("d",arrdate(1),now)
                   
                   
                       strmonth = month(cdate(retDate))
                       strday = day(cdate(retDate))
                       stryear = year(cdate(retDate))
                   
                       If len(strmonth) = 1 Then
                            strmonth = "0" & strmonth
                       End If
                   
                       If len(strday) = 1 Then
                            strday = "0" & strday
                       End If
Else

                        arrdate = split(curvalue,"-")
                        curDate = - cint(arrdate(1))
                       retDate = dateadd("d",curDate,now)
                   
                   
                       strmonth = month(cdate(retDate))
                       strday = day(cdate(retDate))
                       stryear = year(cdate(retDate))
                   
                       If len(strmonth) = 1 Then
                            strmonth = "0" & strmonth
                       End If
                   
                       If len(strday) = 1 Then
                            strday = "0" & strday
                       End If


End If
  
    If Ucase(strParameter1) = "YYYY-MM-DD" Then
        GetDate  = stryear & "-" & strmonth & "-" & strday
    Else
        GetDate  = strmonth & "/" & strday & "/" & stryear
    End If
   
   

End Function

How to verify date format in QTP

Example -


Below code will verify date format in QTP. To verify the dates, you must have actual and expected dates in same format.

So you must convert the dates in a typical format like ddmmyyyy or mmddyyyy etc.

Below function will get the date in mm/dd/yyyy format.
Call Getdate("T") - will return todays date
Call Getdate("T+1") - will return tommorrow's date
Call Getdate("T-1") - Will return previous day's date.
you can calculate any future or past date with this example.


Function GetDate(byval curvalue)
   If  ucase(curvalue) = "T" Then
        curvalue = curvalue & "+0"
   End If


If  instr(1,curvalue,"+") > 0  Then
                        arrdate = split(curvalue,"+")
                       retDate = dateadd("d",arrdate(1),now)
                   
                   
                       strmonth = month(cdate(retDate))
                       strday = day(cdate(retDate))
                       stryear = year(cdate(retDate))
                   
                       If len(strmonth) = 1 Then
                            strmonth = "0" & strmonth
                       End If
                   
                       If len(strday) = 1 Then
                            strday = "0" & strday
                       End If
Else

                        arrdate = split(curvalue,"-")
                        curDate = - cint(arrdate(1))
                       retDate = dateadd("d",curDate,now)
                   
                   
                       strmonth = month(cdate(retDate))
                       strday = day(cdate(retDate))
                       stryear = year(cdate(retDate))
                   
                       If len(strmonth) = 1 Then
                            strmonth = "0" & strmonth
                       End If
                   
                       If len(strday) = 1 Then
                            strday = "0" & strday
                       End If


End If
  
    If Ucase(strParameter1) = "YYYY-MM-DD" Then
        GetDate  = stryear & "-" & strmonth & "-" & strday
    Else
        GetDate  = strmonth & "/" & strday & "/" & stryear
    End If


End Function

How to find length of array in QTP

Example -


Below code will find the length of array  in QTP.

print (ubound(arr) + 1)

Ubound returns the last index in array - so length of array will be +1. This will be total number of elements in array.

How to find array size in QTP

Example -


Below code will find an size of array  in QTP.


print (ubound(arr) + 1)

Ubound returns the last index in array - so size of array will be +1.

How to Find the Length of a string in QTP

Example -


Below code will find the length of string in QTP

print len("sagarsalunke")
' output will be 12

how to delete excel file in qtp

Example -


Below code will delete a Excel file in QTP.

Set fo = createobject("Scripting.filesystemobject")
fo.deletefile("c:\xyz.xlsx")
set fo = nothing

How to Open a excel sheet in QTP

Example -


Below code will open an excel sheet in QTP

 filepath  = "C:\Sai\Report.xlsx"

 Set objExcel = CreateObject("Excel.Application")
                                                                                                                                                 objExcel.Visible = True
                                                                                                                                                       Set Wb = objExcel.Workbooks.Open(filepath)

'After you get reference to workbook, you can access sheets inside it and values as well

e.g.

Wb.worksheets(1).Cells(1,1).Value  = "Scenario Id"
                                                                                                                                                Wb.worksheets(1).Cells(1,2).Value  = "Secnario Name"
                                                                                                                                                Wb.worksheets(1).Columns(1).ColumnWidth  = 10

How to Write a value in excel cell in QTP

Example - 

Below code will Write a value in Excelsheet cell in QTP
                                             
filepath  = "C:\Sai\Report.xlsx"

Set objExcel = CreateObject("Excel.Application")
                                                                                                                                                      objExcel.Visible = True
                                                                                                                                                      Set Wb = objExcel.Workbooks.Open(filepath)
                                                                                                                                                      Wb.worksheets(1).Cells(1,1).Value    = "xyz "       'store xyz in excel cell

How to read value from Excel cell in QTP

Example - 

Below code will read a value from Excel cell in QTP
                                             
 filepath  = "C:\Sai\Report.xlsx"

 Set objExcel = CreateObject("Excel.Application")                                                                                       objExcel.Visible = True
                                                                                                                                                                     Set Wb = objExcel.Workbooks.Open(filepath)
                                                                                                                                                                     print Wb.worksheets(1).Cells(1,1).Value 

  ' read value from Excel cell 1,1

How to Create excel file in QTP

example -


Below code will create new excel file in QTP.
Set objExcel = CreateObject("Excel.Application")
                                                                                                                                            objExcel.Visible = True
Set Wb = objExcel.Workbooks.Add()
                                                                                                                                                Wb.worksheets(1).Cells(1,1).Value  = "Scenario Id"
                                                                                                                                                Wb.worksheets(1).Cells(1,2).Value  = "Secnario Name"
                                                                                                                                                Wb.worksheets(1).Columns(1).ColumnWidth  = 10
                                                                                                                                                Wb.worksheets(1).Columns(2).ColumnWidth  = 40
                                                                                                                                                Wb.worksheets(1).Columns(3).ColumnWidth  = 20
                                                                                                                                                Wb.worksheets(1).Columns(4).ColumnWidth  = 20

                                                                                                                                                                                                Wb.SaveAs "c:\ayx.xlsx"  ' save file in say "c:\ayx.xlsx"
                                                                                                                                                                                                Wb.close
                                                                                                                                                                                                objExcel.Quit
                                                                                                                                                                                                blnFlag = False

Types of the Environment Variables in QTP

QTP has basically 2 types of environment variables.


  • Built in - e.g OS - operating system information - This is read only
  • User Defined - User can define his own variables - This can be edited or modified.
User defined variables can be loaded from external variables as well. When you load it from the external file, Variables can not be edited.

To create user defined variables, you have to go to the settings of the test and click on environment Tab.
Select variable type as "User defined". Then add any variable and it's value.

Example -

'Create environment variable at runtime -
Environment.Value("MyDirectory") = "c:\test"

Environment.LoadFromFile "c:\Env.ini"   ' Load varaibles from ENV.ini

Format of ini file should be like this -

[Environment]
 
   var1=abcd
   var2=xyz

[Environment]

How to Double Click in QTP

Example -


To double click on any object in QTP you can use fireevent method as shown below.


Browser("my").Page("myp").WebElement("innertext:=sagar").FireEvent "ondblclick"

How to Exit For Loop in QTP

To get Exit for loop in QTP you must use Exit For Statement.

Exit For  statement will get the control out of the for loop and execute first statement  outside for loop.

Example -
Below code demonstrates the exit for use in QTP -

    For ct = 1 to 3
             TempNum = mid(Tempstr,ct,1)
              If isnumeric(TempNum) Then
                LengthNum = LengthNum &TempNum
               Else
                  Exit For
               End If
            Next
        GetStrLenNumber = LengthNum

How to open Browser in QTP

There are 3 ways in which you can open a browser in QTP.


  • SystemUtil.Run "iexplore.exe" , "http://www.google.com",,,3
  • Shell Object
  • Invokeapplication - InvokeApplication "C:\Program Files\Internet Explorer\IEXPLORE.EXE http://www.yebhi.com"
using shell object also you can open a browser like this - >

Dim oShellSet oShell = CreateObject ("Wscript.shell")

oShell.Run  "C:\Program Files\Internet Explorer\IEXPLORE.EXE"

Set oShell = Nothing

How to add synchronisation points in QTP

There are 4 ways in which we can add synchronisation  points in QTP .

  • Wait statement - This statement will pause the execution for x seconds until object comes up.
  • Waitproperty - This method will wait until property of object takes particular value
  • Exist statement - This statement will wait until object becomes available.
  • sync method - This method is used in web application testing. Used to wait until page loads.
Examples  -

Wait statement
Wait 2   ' wait for 2 seconds
'Wait statement should be used rarely as it suspends the execution of the script for the fixed amount of time.
'Unless you know exact amount of time, you should not use wait statement. This will slow down execution

WaitProperty method
To eliminate the problem associated with wait statement, we can use either waitproperty or exist method.
In  waitproperty and  exist methods, we do not wait for the fixed amount of the time but for only required amount of time.

In case of waitproperty, we wait until particular property value becomes the expected one. We can also specify the time out.

Example -
ActiveX("panel").WaitProperty "text", "Done", 4000

'This code  will wait until text property of panel object becomes Done. Max timeout is 4 seconds. That means the QTP will wait for the maximum time of 4 seconds. If the text property becomes Done in say 2 second then QTP will jump to next statement in the script.

Exist method
To eliminate the problem associated with wait statement, we can also use exist method.
In case of exist method, we wait until particular object becomes available. We can also specify the max time out.

If window("mywin").Exist(5) Then
   'do some operation
    'In This code QTP waits until mywin window object is displayed
Else
    print "mywin window does not exist even after waiting for 5 seconds"  
End If

Sync method
sync method can be used only in case of web application testing. Browser("myb").sync  'This code will wait untill browser page is completely loaded.

How to Associate Function Library in QTP

Well - we can associate function library to QTP Test either manually or by automation code.


  • Manually with Test Settings - In this method you have to go to Test Settings->Resources and add any library file. library File can have 3 extentions - .vbs, .qfl or .txt
  • By Automation Code, You have to use below code.

    Set App = CreateObject("QuickTest.Application")
    If App.Launched Then ' If QuickTest is  open
            App.Quit
    End If
    App.Launch
    App.Visible = True
    App.Open Testpath
   
    Set qtplib = App.Test.Settings.Resources.Libraries
   
    qtplib.RemoveAll   
    qtplib.add "c:\lib1.vbs"
    App.Test.Save


This code will associate lib1.vbs file with test viz. Testpath 

How to Associate Object Repository to QTP Test

Well - we can associate object repository to QTP Test either manually or by automation code.


  • Manually with Test Settings - In this method you have to go to Resources->Associate repositories. Here you can give the path of tsr file that is Shared OR.
  • By Automation Code, You have to use repositories collection object as mentioned in below code.
Dim QTPAPP
Dim qtObjRes 

Set QTPAPP= CreateObject("QuickTest.Application") 
QTPAPP.Launch
QTPAPP.Visible = True 
 
QTPAPP.Open "C:\Test\Testabc", False, False 
 
Set qtObjRes = QTPAPP.Test.Actions ("Login").ObjectRepositories 
 
qtObjRes.Add "C:\OR\myRes.tsr", 1 
 
In this code , Login action will have myres.tsr associated with it. 

How to break for loop in QTP

To get out of for loop in QTP you must use Exit For Statement.

Exit For  statement will break the for loop and execute first statement  outside for loop.

Example -
Below code demonstrates the exit for use in QTP -

    For ct = 1 to 3
             TempNum = mid(Tempstr,ct,1)
              If isnumeric(TempNum) Then
                LengthNum = LengthNum &TempNum
               Else
                  Exit For
               End If
            Next
        GetStrLenNumber = LengthNum

How to Bypass Object Repository (OR) in QTP

Yes - we can do automation of any application bypassing the OR. I know you must be knowing how we can do it.


Using descriptive programming we can easily bypass OR.

Code below will make you understand how to bypass OR in QTP.

                 Set objLinkDash = Description.Create
                objLinkDash("micclass").Value = "Link"
                objLinkDash("html tag").Value = "A"

                Set lnkObj=constobjParent.childobjects(objLinkDash)

                For i=0 to lnkObj.count-1
                print lnkObj(i).getROProperty("innertext")
                Next

Note that we have not used any object from OR in above code.

How to select webradio button in QTP

Well - It is very easy to select webradio button. We need to just use click method of webradio object.

This will do the job.

Example -

Browser("myb").Page("myp").webradio("myr").click

That is it!!!!!!!!

How to Handle Multiple Browsers in QTP

There are 2 ways in which we can handle mutiple browsers in QTP.


  • Using Creation Time ordinal identifier in QTP.
  • Using hwnd property of browsers in QTP.
We can get handles of all browsers with below code


Set BrowserObj = Description.Create
BrowserObj("micclass").Value = "Browser"
Set Obj = Desktop.ChildObjects(BrowserObj)

For i=0 to obj.count-1
print obj(i).getROProperty("hwnd")
Next

Find out all open browsers in QTP

Below Code will print the titles of all browsers that are open in the system.


Set BrowserObj = Description.Create
BrowserObj("micclass").Value = "Browser"
Set Obj = Desktop.ChildObjects(BrowserObj)

For i=0 to obj.count-1
print obj(i).getROProperty("Title")
Next

How to create a Shared Object Repository in QTP

Please follow the steps given below to create a shared Object Repository in QTP.

  • Open Local Or
  • Go to File->Export Local Objects
  • Save file as abc.tsr
So abc.tsr will be a shared OR and we can associate it with ant test.

Cross Browser Testing using Selenium WebDriver_Selenium online Training

In this post I am going to explain how can we do Cross Browser Testing using Selenium.

If we are using Selenium WebDriver,In order to execute test cases using different browsers like Firefox, Chrome, Opera ,Internet Explorer we have to use TestNG framework.

 Test.xml :
In TestNG, if we want execute same test case with different browsers we have to use Test.xml file.

Sample Code:
<suite name="CrossBrowserTesting" preserve-order="true" parallel="false" >
   
<test name="Smoketest" preserve-order="true">

<parameter name="browserName" value="firefox"></parameter>
<!-- 
<parameter name="browserName" value="ie"></parameter>
<parameter name="browserName" value="chrome"></parameter>
<parameter name="browserName" value="opera"></parameter>
 -->
<classes>

<class name="Configuration.HMSLogin"></class> 
  
</classes>

</test>

</suite>

BrowserType.java

We have to pass "browserName" parameters from Test.xml and it will map with the BrowserType.java using @Parameters  annotation.
And the BrowserType.java will look like below
Sample Code:
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.opera.OperaDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;

public class BrowserType {

public static WebDriver driver;
@BeforeClass
@Parameters("browserName")
public void setup(String browserName) throws IOException, InterruptedException{

//open Firefox Browser 
//open the browser based on parameter passed in .xml file.
if(browserName.equalsIgnoreCase("firefox")){

//if you are using selenium 2.0
driver = new FirefoxDriver();

//if you are using selenium 3.0
//System.setProperty("webdriver.gecko.driver", "path/to/geckodriver.exe");
//driver = new FirefoxDriver();
}
else if(browserName.equalsIgnoreCase("chrome")){

//open chrome browser
System.setProperty("webdriver.chrome.driver", "E:/Selenium Training/Driver Files/chromedriver.exe");
driver= new ChromeDriver();
}

else if(browserName.equalsIgnoreCase("ie")){
//open Internet Explorer Browser
System.setProperty("webdriver.ie.driver", "E:/Selenium Training/Driver Files/IEDriverServer.exe");
driver= new InternetExplorerDriver();

}
else if(browserName.equalsIgnoreCase("opera")){
//open opera Browser
System.setProperty("webdriver.opera.driver", "E:/Selenium Training/Driver Files/operadriver.exe");
driver= new OperaDriver();

}
//maximizing window
driver.manage().window().maximize();

//Navigating URL
driver.get("http://selenium4testing.com/hms/index.php?");

}
}

Testcase:
We have to extends BrowserType class to each test-suite and it will look like below
Sample Testcase code:
import org.openqa.selenium.By;
import org.testng.annotations.Test;

public class HMSLogin extends BrowserType {
@Test(priority=1)
public void Login() {

driver.findElement(By.xpath("//input[@name='username']")).clear();
driver.findElement(By.xpath("//input[@name='username']")).sendKeys("admin");

driver.findElement(By.xpath("//input[@name='password']")).clear();
driver.findElement(By.xpath("//input[@name='password']")).sendKeys("admin");

driver.findElement(By.xpath("//input[@name='submit']")).click();

}

}


finally execute the Test-suite by using Test.xml file.

Handle multiple windows using selenium webdriver in different ways_Selenium online Training

There are many applications,where a link display on new window or tab when you click on it. 
In that situation we have to switch driver focus from parent to child window and vice versa

In this post, I will explain how can we handle multiple windows using windows Handlers in selenium webdriver.

We can handle multiple windows using window handlers in two ways.

1)Using For-Each Loop
2)Using For Loop

1.Using For-Each Loop:
Sample code:
public class HandleWindows {
public WebDriver driver;

@BeforeClass
public void setup() throws InterruptedException{
driver = new FirefoxDriver();
driver.get("http://www.way2selenium.com/");
Thread.sleep(5000);
driver.manage().window().maximize();
}
@Test
public void test(){

//To get the window id of the current window
String currentWindow = driver.getWindowHandle();

//Clicking on on share link on current window which will open in new window
driver.findElement(By.xpath("//span[contains(.,'Share to Facebook')]")).click();

//To get the window id's of all the current windows
Set<String> windows = driver.getWindowHandles();

//for each method for identifying child window
for(String ChildWindow:windows){

//switching from current window to child window
driver.switchTo().window(ChildWindow);

}

//Maximize child window
driver.manage().window().maximize();

//get the title from child window
System.out.println(driver.getTitle());

//Closing child window
driver.close();

//switch back from child to current window
driver.switchTo().window(currentWindow);

//get the title from current window
System.out.println(driver.getTitle());

//Closing current  window
driver.close();
}


2.Using For Loop:
Sample Code:
public class HandleWindows3 { public WebDriver driver; @BeforeClass public void setup() throws InterruptedException{ driver = new FirefoxDriver(); driver.get("http://www.way2selenium.com/"); Thread.sleep(5000); driver.manage().window().maximize(); } @Test public void test(){ //To get the window id of the current window String currentWindow = driver.getWindowHandle(); //Clicking on on share link on current window which will open in new window driver.findElement(By.xpath("//span[contains(.,'Share to Facebook')]")).click(); //For loop for identifying child window Set<String> allWindowHandles = driver.getWindowHandles(); Iterator<String> iter=allWindowHandles.iterator(); int size=allWindowHandles.size(); String child = null; for(int i=0;i<size;i++){ child=iter.next(); } //switching from current window to child window driver.switchTo().window(child); //Maximize child window driver.manage().window().maximize(); //get the title from child window System.out.println(driver.getTitle()); //Closing child window driver.close(); //switch back from child to current window driver.switchTo().window(currentWindow); //get the title from current window System.out.println(driver.getTitle()); //Closing current window driver.close(); } }