Thursday, 18 December 2014

Tips and Tricks for working with UFT?

Just for a change we tend to thought of attempting some out of way features offered in UFT.

We implemented the Runners logic:-i'm tired...i think i'll opt for a run.
We were tired of sharing orthodox topics, so we thought lets share some less browse topics, Hope it motivates our followers to learn more and grow more

Do like our FB page, Twitter, or G+ for more learning.


Learn UFT
Run more learn more
@PhotoCourtsey

Scenario1:-
What can be an alternate approach in case “OpenNewTab” function of webbrowser is not working
a)Using Native object method to open new tab.

Systemutil.Run "iexplore.exe","google.com"
Browser("creationtime:=0").Object.Navigate "YAHOO.COM",Clng(&H800)

Note:-Please close all browsers before running the code, as we have used Creationtime property it might create a conflict in UFT mind.

b)Using Descriptiveprogramming
Systemutil.Run "iexplore.exe","google.com"
Set obj =Browser("Creationtime:=0").WinObject("object class:=window")
obj.WinButton("acc_name:=New Tab \(Ctrl\+T\)").Click
Browser("CreationTime:=1").Navigate "google.com"
Set obj = Nothing


Scenario2:-
How to Split string in case we have inconsistent values of delimiter (We have taken space as a delimiter in our case, and we are not sure how many spaces separates consecutive words.)

Code:-
sInput = "uftHelp=  User Firendly      Techy Help"
fn_SplitMe sInput,"  "
Public function fn_SplitMe(sTest,sDelimit)
    Dim arrData
    'Split the input string on the basis of Delimiter 
    arrData = split(sTest,sDelimit)
    Dim arrNew():Dim j :j= 0 
    'Looping through all the elements to separate the Text and Delimiter
    For iCnt = 0 to ubound(arrData)
     If not arrData(iCnt) = "" Then
         Redim Preserve arrNew(j)
         arrNew(j) = arrData(iCnt)
         j = j+1
     End If
    Next
    'Printing the separated values
    for each val in arrNew
        Print Trim(val)
    Next 
End Function 

Output:-
Based on the delimiter selected we would have different set of output values.
Split function in UFT
Output results for varying delimiter 
Scenario 3:- 
How to select a random values from a weblist
Weblist select random values in UFT
Example Weblist
'Selecting a random value from the weblist 
Dim iRand :iRand = 0
'RandomNumber is a Utility Object,(1,103)specifies its
'lower & Upper range for generating random values
iRand = RandomNumber(1,103)
Dim objTest : Set objTest = ""
'Creating the main Browser object
Set objTest = Browser("CreationTime:=0").Page("Index:=0")
'Ist Approach
objP.WebList("wl_Test").Object.selectedIndex = iRand
'2nd Approach 
objP.WebList("wl_Test").Select "#"&iRand
 

Scenario 4:-
How we can ignore a given browser or an ALM session when UFT is executing scripts.Suppose our requirement is to close all the browser before the run of test suite except ALM instance or “chrome” browser

Step1:-
Tools ->Options ->GUI Testing ->Web


Ignore ALM in Run UFT
Ignore browser in UFT

Browser details to ignore UFT
Browser Details 

Step2:-
Click on + symbol to add the browser details to be ignored, we can use title or URL of the browser.Also for ALM we can just select the option ignore ALM.

Scenario 5:-
How to change the run settings in UFT, so that it replicates the typing of keyboard on a webedit, rather than directly settings the value.

Requirement: - we want to type a value into a web edit on google search rather than putting all the value in one go.
Note: - WebEdit does not support the Type method, it is only present with window applications. We can implement send keys to achieve this but here we are focusing on UFT level settings to achieve the same.
Approach:-
Change the Replay Type to “Mouse” by using the path: - Tools->options->GUI Testing ->Web->Advance->Run Settings->Replay Type ->Mouse
Change replay type in UFT settings
Options window in UFT
Try the following code before and after doing the changes and check the difference

'launch browser maximized
SystemUtil.Run "chrome.exe","google.com",,,3
'Create object of webedit
Set obj =Browser("creationtime:=0").Page("creationtime:=0").WebEdit("html id:=gbqfq")
'Setting value into Google search text box
obj.Set "This is really long text that we are writing to check the Type effect"


Keep learning and keep sharing

Wednesday, 17 December 2014

Parallel execution of Tests in TestNG

Scenario:-
How we can achieve running of parallel set of tests in TestNG.
Parallel run in Selenium
Parallel Run
Solution:-
We are already done with cross browser testing using TestNG, we would utilize the same example here to design our solution.

Test Scenario:-
We want parallel instances of Test Case one in Firefox and another in Chrome, but with different set of data.
Example:-
Firefox with 'username1' and 'password1'
Chrome with 'username2' and 'password2

Approach:-
We would use the @parameter annotation to create different set  of data.
Also we would add,'Parallel' attribute in the Suite tag of XML file, this  is being used to run tests parallel in different browsers.
And 'thread-count' attribute is to used to pass the number of maximum threads to be created.

XML File:-
<?xml version="1.0" encoding="UTF-8"?>
<suite name="Suite" parallel="tests" thread-count="2">
 <test name="Run in Firefox">
  <parameter name="browser" value="firefox"></parameter>
  <parameter name="userName" value="Test1"></parameter>
  <parameter name="Password" value="Pwd1"></parameter>
  <classes>
   <class name="srcTest.ParallelTesting"/>
  </classes>
 </test>
 <test name="Run in chrome">
  <parameter name="browser" value="chrome"></parameter>
  <parameter name="userName" value="Test2"></parameter>
  <parameter name="Password" value="Pwd2"></parameter>
  <classes>
   <class name="srcTest.ParallelTesting"/>
  </classes>
 </test>
</suite>

Java Code:-
package srcTest;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class ParallelTesting {
 private WebDriver driver;
 @Test
 @Parameters({"userName","Password"})
 public void login(String userName,String Password)
 {
  //Adding Implicit wait 
  driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
  //Maximize browser
  driver.manage().window().maximize();
  //Open the Login Application
  driver.get("http://www.ufthelp.com/p/testpage.html");
  //Fill the UserName and Password fields
  driver.findElement(By.id("userName")).sendKeys(userName);
  driver.findElement(By.id("password")).sendKeys(Password);
  //Click the Sign in Button
  driver.findElement(By.id("SignIn")).click();
  //Clicking on the alert message
  driver.switchTo().alert().accept();
  
 }

   @BeforeClass
   @Parameters({"browser"})
   public void BeforeClass(String browser) throws Exception {
   //Incase it is firefox browser 
   if(browser.equals("firefox"))
   {   
    driver = new FirefoxDriver();
   }
   //Incase browser is chrome
   else if(browser.equals("chrome"))
   {
     System.setProperty("webdriver.chrome.driver", "D:\\Automation\\Selenium\\MyCode\\chromedriver_win32\\chromedriver.exe");
     driver = new ChromeDriver(); 
   }
   //Exit the Test without execution
   else
   {
   //Throw an exception for no matching browsers    
        throw new Exception("Invalid Browser"+browser);
          }  
   
  }
 
   @AfterClass
   public void afterClass() {
  //Destroying the object
  driver.quit();
   }

}


More Testing Scenarios

@PhotoCourtsey

Uninstall Plugin/Addin in Eclipse

Scenario:-
We want  to uninstall a Plugin added in eclipse (say TestNG)?
Solution:-
After installation of any plugin, incase we don't need it we can uninstall it using following steps
Step1:-
Launch Eclipse IDE, Help ->Install New Software
Uninstall new software in Eclipse
Install New Software





Step2:-
On “Available Software” window, Click on “already installed” link
Already Installed Softwares in Eclipse
Already Installed Softwares
Step3:-
On “Eclipse Installation Details”, window, Select the Name -> Uninstall
Installation Details in Eclipse
Installation Details Window
Step4:-
On “Uninstall Details” window, Click Finish.
It will take few seconds to uninstall the plugin
Uninstall Plugin Eclipse
Uninstall Window Eclipse
Step5:-
Restart Eclipse.
Restart eclipse after uninstallation
Restart Eclipse
Step6:-
We can verify the uninstallation, by opening the “Eclipse Installation Details” window (Help->Install new Software ->already installed)

Uninstall verified in Eclipse
Verify un installation of Plug in


Installation of TestNG in Eclipse

After our introduction to TestNG, we are moving towards its installation as an Add-in in Eclipse.For this we need Eclipse on our system and an internet connection.

Also there is no need to download any Jar file or exe file for installation.  We need to just utilize the “Install New Software” option available in the Eclipse.

Step1:-
Launch Eclipse IDE -> Help -> Install new Software
Install new software in Eclipse
Install New Software

Step2:-
a.Click Add on "Available Software" window
Available software window in Eclipse
Available Software
b.Fill the details on "Add Repository" window, i.e Name,(say TestNG) and  location = "http://beust.com/eclipse" ->Click OK
Beust to remind You is the creator of TestNG
TestNG Location URL
Add Name and Location of TestNG 

Step3:-
Select TestNG in Available Software list window -> Click Next
Select TestNG from Available Software
Select TestNG 
Step4:-
Accept the license Agreement -> Finish
License Agreement Window
License Agreement Window
Note:- Incase of any warning message popup comes , click OK 
Security Warning in Eclipse
Security Warning Message
Step5:- 
Restart Eclipse
Restart Eclipse window after Software Updates
Restart Eclipse window
Step6:-
Verify TestNG is successfully installed.
Right click on the Java Project in the solution explorer and check that TestNG option is available.
Solution Explorer with TestNg
TestNG is Installed
Writing our First Test Case using TestNG

Tuesday, 16 December 2014

How to do Cross Browser testing using Selenium

What is Cross Browser Testing Concept?
In today’s world we as users have numerous list of available browsers, which introduces problems for web-application developers. Because web applications are expected to behave consistently across all of these browsers. However, because the standards for client-side technology are still evolving, there is a great deal of inconsistency in how different web browsers behave. These inconsistencies lead to what we call cross browser issues–differences in the way a web page looks and behaves in different browsers.
So we need to move towards cross browser testing.(Testing web applications across multiple combinations of browsers)
Multi browser testing selenium
Cross Browser Testing 

Cross-browser issues can range from minor cosmetic problems like layout issues (differences in element position, size, visibility, or appearance.) to critical failures that involve the inaccessibility applications functionality. In both cases, the issue can result in the inability of the users to
Perform one or more services provided by a web application, which results in losing of business. For example we are on amazon buying page but buy button is not visible in xyz browser, are we going to wait for that button or move to eBay to buy the same product.

Please read the below topic only in case you are curious about how browsers work, else skip directly to the code part :)

Web Browser rendering:-
A web application follows a typical client-server computing model and usually consists of several server and client side components. Server side components get invoked when the web server receives a request (typically, from a remote user through a web browser like searching selenium tutorials on google). As a result of the server side execution, various client side components are dynamically generated and sent back to the web browser in the form of HTML pages. These pages, which are rendered by the browser, reference or contain resources such as images, animations, style information (i.e,
Cascading Style Sheets (CSS)) and scripts (e.g., JavaScript or VBScript).

Now on client end meaning a web browser, it  consists of different subsystems that handle numerous functionalities, such as processing the client side components and managing the interactions of these components with system resources (e.g., network, display, file system).Among the subsystems of a browser, one of the main components is the layout engine(we are interested in this), which is responsible for rendering a web page by parsing the HTML tags in the page and applying to the relevant elements the style information contained in the CSS style sheets for the page. The browser also maintains a DOM
(Document Object Model) representation of the web page in its memory to allow scripts associated with the page to query and modify web page elements. Although there is a standard definition for the DOM format, web browsers often deviate from such standard. Moreover, since most web pages have browser specific code to make them work on different browsers and platforms, the DOM
generated by different browsers can be very different, resulting in different rendering of elements on web browsers. So we move towards cross –browser testing.

Approach:-
We are going to leverage the data parameterization feature of TestNG to achieve cross browser testing in Selenium.

Code:-
package srcTest;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.AfterClass;

public class CrossBrowser {
 private WebDriver driver;
 @Test
 public void login()
 {
  //Adding Implicit wait 
  driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
  //Maximize browser
  driver.manage().window().maximize();
  //Open the Login Application
  driver.get("http://www.ufthelp.com/p/testpage.html");
  //Fill the UserName and Password fields
  driver.findElement(By.id("userName")).sendKeys("uftHelp");
  driver.findElement(By.id("password")).sendKeys("Password");
  //Click the Sign in Button
  driver.findElement(By.id("SignIn")).click();
  //Clicking on the alert message
  driver.switchTo().alert().accept();
  
 }

   @BeforeClass
   @Parameters({"browser"})
   public void BeforeClass(String browser) throws Exception {
   //Incase it is firefox browser 
   if(browser.equalsIgnoreCase("firefox"))
   {   
    driver = new FirefoxDriver();
   }
   //Incase browser is chrome
   else if(browser.equalsIgnoreCase("chrome"))
   {
     System.setProperty("webdriver.chrome.driver", "D:\\Automation\\Selenium\\MyCode\\chromedriver_win32\\chromedriver.exe");
     driver = new ChromeDriver(); 
   }
   //Exit the Test without execution
   else
   {
   //Throw an exception for no matching browsers    
        throw new Exception("Invalid Browser"+browser);
          }  
   
  }
 
   @AfterClass
   public void afterClass() {
  //Destroying the object
  driver.quit();
   }

}

XML File:-
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Suite" >
 <test name="Run in Firefox">
  <parameter name="browser" value="firefox"></parameter>
  <classes>
   <class name="srcTest.DataParameterization"/>
  </classes>
 </test>
 <test name="Run in chrome">
  <parameter name="browser" value="chrome"></parameter>
  <classes>
   <class name="srcTest.DataParameterization"/>
  </classes>
 </test>
</suite>


Result:-



Note:-While running the same code on different browsers we can have issues like Speed of execution, when things execute too quickly (which indicates that you need to add explicit waits to your test code) or timeout (which indicates that the explicit waits you have are too tight and need to be loosened). To avoid such scenarios we need to test the code on individual browsers and find the failures. Take each failed test, adjust the code as needed, and re-run until everything's green.

How to write selenium test case using TestNG?

First TestCase in TestNG

We are already done with the introduction and installation of TestNG, today we are writing our first test case in TestNG.

Scenario:-How to execute our First Test Case using TestNG

Solution:-
Step 1:-Adding TestNG class
A:-Press CTRL+N ->TestNG->Create TestNG Class
Creating TestNG Class
Creating TestNG Class

B:-Set Class Name and select Annotations ->Finish
Selecting Annotation while creating TestNG Class
Class name + Annotations
Step 2:-Adding the code to the new Class
A. @BeforeMethod:-Launch Browser and its settings.
B. @Test:- Our Login Test Case
C. @AfterMethod:-Quit Browser


View of TestNG class with Annotations
Default view of TestNG Class with Annotations

Code:-


package srcTest;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;

public class FirstTest {
private WebDriver driver;
   @Test
   public void login() {
  //Fill the UserName and Password fields
  driver.findElement(By.id("userName")).sendKeys("uftHelp");
  driver.findElement(By.id("password")).sendKeys("Password");
  //Click the Sign in Button
  driver.findElement(By.id("SignIn")).click();
  //Clicking on the alert message
  driver.switchTo().alert().accept();
   }
   @BeforeMethod
   public void beforeMethod() {
   driver = new FirefoxDriver();
  //Adding Implicit wait 
  driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
  //Maximize browser
  driver.manage().window().maximize();
  //Open the Login Application
  driver.get("http://www.ufthelp.com/p/testpage.html");
   }
 
   @AfterMethod
   public void afterMethod() {
  //Closing the browser
  driver.quit();
   }

}

Step 3:-Running the Code
RightClick on the TestCase ->Run As -> TestNG Test
or
CTRL+F11

Step 4:-Observing the Run Results
Eclipse will have results in Console window, while TestNG result will be shown separately in "Results of Running class TestName".
Result of running class using TestNG
Run Results of TestNG

Step 5:-Checking the HTML Reports
Method1:-We can go to the Project Directory ->test-output folder 


test-output folder in TestNG
Open the test-output folder inside the Project Directory
How to locate the Project Directory? 
Right click in the solution explorer ->Properties


Project directory path in eclipse
Path of project directory 
Method2:-In the solution explorer ->test-output->index.html (it will show the latest run results)


index.html file in test-output folder in eclipse
index.html file in test-output folder in solution explorer
Open index.html in browser
Opening the index.html file
Test results in TestNG
Test Results - TestNG



We can open the emailable-report.html from test-output folders.

Emailable view of the test results in TestNG
Emailable view of the results in TestNG
Data Parameterization in TestNG