Sunday, 18 January 2015

How to works with Ajax controls using Selenium Webdriver

AJAX stands for Asynchronous JavaScript and AJAX allows the Web page to retrieve small amounts of data from the server without reloading the entire page. In AJAX driven web applications, data is retrieved from server without refreshing the page.

When we perform any action on Ajax controls, using Wait commands will not work as the page is not actually refreshed here. Pausing the test execution using threads for a certain period of time is also not a good approach as web element might appear later or earlier than the stipulated period of time depending on the system’s responsiveness, load or other uncontrolled factors of the moment, leads to test failures.

The best approach would be to wait for the required element in a dynamic period and then continue the test execution as soon as the element is found/visible.

This can done achieved with WebDriverWait in combination with ExpectedCondition , the best way to wait for an element dynamically, checking for the condition every second and continuing to the next command in the script as soon as the condition is met.

There are many methods which are available to use with wait.until(ExpectedConditions.anyCondition); The below is the image for the number of methods which are available.
The below are the few which we use regularly when testing an application :-

Syntax:
WebDriverWait wait = new WebDriverWait(driver, waitTime); wait.until(ExpectedConditions.presenceOfElementLocated(locator));

The above statement will check for the element presence on the DOM of a page. This does not necessarily mean that the element is visible.

Syntax:
WebDriverWait wait = new WebDriverWait(driver, waitTime); wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
 
The above syntax will for the element present in the DOM of a page is visible.
Some times we may also need to check if the element is invisible or not. To do this we need use the below :

Syntax:
WebDriverWait wait = new WebDriverWait(driver, waitTime); wait.until(ExpectedConditions.invisibilityOfElementLocated(locator));

Some times you will get an exception as ""org.openqa.selenium.WebDriverException: Element is not clickable at point (611, 419). Other element would receive the click:'. The below one is used to wait for the element to be clickable.

Syntax:
WebDriverWait wait = new WebDriverWait(driver, waitTime); wait.until(ExpectedConditions.elementToBeClickable(locator));


------------------------------------------------------------------------------------------------------------------
package com.pack.ajax;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class AjaxExample {
 
 private String URL = "http://demos.telerik.com/aspnet-ajax/
                                  ajax/examples/loadingpanel/explicitshowhide/defaultcs.aspx";
 
 WebDriver driver;
 WebDriverWait wait;
 
 @BeforeClass
 public void setUp() {
  driver=new FirefoxDriver();
  driver.manage().window().maximize();
  driver.navigate().to(URL);
 }
 
 @Test
 public void test_AjaxExample() {

  /*Wait for grid to appear*/
  By container = By.cssSelector(".demo-container");
  wait = new WebDriverWait(driver, 5);
  wait.until(ExpectedConditions.presenceOfElementLocated(container));
  
  /*Get the text before performing an ajax call*/
  WebElement noDatesTextElement = driver.findElement(By.xpath("//div[@class='RadAjaxPanel']/span"));
  String textBeforeAjaxCall = noDatesTextElement.getText().trim();
  
  /*Click on the date*/
  driver.findElement(By.linkText("1")).click();
 
  /*Wait for loader to disappear */
  By loader = By.className("raDiv");
  wait.until(ExpectedConditions.invisibilityOfElementLocated(loader));
  
  /*Get the text after ajax call*/
  WebElement selectedDatesTextElement = driver.findElement(By.xpath("//div[@class='RadAjaxPanel']/span"));
  wait.until(ExpectedConditions.visibilityOf(selectedDatesTextElement));
  String textAfterAjaxCall = selectedDatesTextElement.getText().trim();
  
  /*Verify both texts before ajax call and after ajax call text.*/
  Assert.assertNotEquals(textBeforeAjaxCall, textAfterAjaxCall);
  
  String expectedTextAfterAjaxCall = "Thursday, January 01, 2015";
  
  /*Verify expected text with text updated after ajax call*/
  Assert.assertEquals(textAfterAjaxCall, expectedTextAfterAjaxCall);
 }

}
  
------------------------------------------------------------------------------------------------------------------

Tuesday, 25 November 2014

Connect Database Using Selenium WebDriver

Tutorial Connecting to DataBase using Selenium WebDriver 

Web Driver cannot directly connect to Database. You can only interact with your Browser using Web Driver. For this we use JDBC("Java Database Connectivity").The JDBC API is a Java API for accessing virtually any kind of tabular data.The value of the JDBC API is that an application can access virtually any data source and run on any platform with a Java Virtual Machine.

In simplest terms, a JDBC technology-based driver ("JDBC driver") makes it possible to do three things:

1.Establish a connection with a data source
2.Send queries and update statements to the data source
3.Process the results

 1.Establish a connection with a data source
The traditional way to establish a connection with a database is to call the method
DriverManager.getConnection(URL,  "username", "password" )
URL :   jdbc:<subprotocol>:<subname>
<subprotocol>-the name of the driver or the name of a database connectivity mechanism
<subname> - The point of a subname is to give enough information to locate the data source .(Includes IP address , Port number and exact name of DataSource)

For connecting to MYSQL URL will be
jdbc:mysql://localhost:3306/hoale

2.Send queries and update statements to the data source
A Statement object is used to send SQL statements to a database over the created connection in Step 1.
Statement-created by the Connection.createStatement methods. A Statement object is used for sending SQL statements with no parameters.
PreparedStatement-created by the Connection.prepareStatement methods. A PreparedStatement object is used for precompiled SQL statements. These can take one or more parameters as input arguments (IN parameters).
CallableStatement-created by the Connection.prepareCall methods. CallableStatement objects are used to execute SQL stored procedures
In Short
createStatement methods-for a simple SQL statement (no parameters)
prepareStatement methods-for an SQL statement that is executed frequently
prepareCall methods-for a call to a stored procedure

3.Process the results
A ResultSet is a Java object that contains the results of executing an SQL query.We will have separate post on it.The JDBC API provides three interfaces for sending SQL statements to the database.

Prerequisites:
-      mysql-connector-java-5.1.0-bin.jar  or above versions
-      Create table Employee in Navicat
-      Reading a old http://howtesting.blogspot.com/2013/01/creating-html5-page.html create a sample webform
This is example for connection DataBase(mysql) using Selenium WebDriver

 

package com;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.mysql.jdbc.ResultSet;
import com.mysql.jdbc.Statement;
import com.thoughtworks.selenium.SeleneseTestBase;
public class ConnectDB extends SeleneseTestBase{
     WebDriver driver;
     String url ="";
     @BeforeTest
public void setUp() throws Exception{
     driver = new FirefoxDriver();
     url = "file:///D:/ECLIPSE/workspace_eclipseclassic/ConnectDB/src/com/modules/HTML5Demo.html";
     driver.get(url);
}
     @Test
     public void CreateDB() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException{
           //Prepare connection
           String url1 ="jdbc:mysql://localhost:3306/hoale";
           // Load Microsoft SQL Server JDBC driver
           String dbClass = "com.mysql.jdbc.Driver";
           Class.forName(dbClass).newInstance();
           //Get connection to DB
           Connection con = DriverManager.getConnection(url1, "root", "");
           //Create Statement
           Statement stmt = (Statement) con.createStatement();
           // method which returns the requested information as rows of data
           ResultSet result = (ResultSet) stmt.executeQuery("select * from employee");
           if(result.next())
           {
                String id = result.getString("ID");
                String info = result.getString("Info");
                driver.getCurrentUrl();
                WebElement a = driver.findElement(By.id("txtID"));
                a.sendKeys(id);
                WebElement b = driver.findElement(By.id("txtInfo"));
                b.sendKeys(info);
                WebElement btnclick = driver.findElement(By.id("btnclick"));
                btnclick.click();
                System.out.print("Passed");
           }
     }
    
     @AfterTest
public void tearDown(){
     driver.close();
}
}

 

Friday, 25 July 2014

Basics of TestNG Frameworks

TestNG Framework

TestNG is testing framework inspired from JUnit and NUnit but introducing some more new functionality that makes it more powerful  and easier to use. It is open source automated testing framework.

Benefits of TestNG

1. It gives you HTML report of execution.
2. Annotation in TestNG make tester's life easy.
3. Test cases can grouped together and prioritized in well manner.
4. Parallel testing is possible and we can generates logs also by enabling log4j.xml.

Test Case Writing

1. Very first thing is, write the business logic of the test.
2. Use TestNG annotations in the your test code.
3. Add the information about your test (e.g. Class names, methods names, groups names..) in testng.xml file.
4. Once xml is redy with everything run it as TestNG.

Annotations in TestNG

@BeforeSuite: The annotated method will be run before all tests in this suite have run.
@AfterSuite: The annotated method will be run after all tests in this suite have run.
@BeforeTest: The annotated method will be run before any test method belonging to the classes inside the tag is run.
@AfterTest: The annotated method will be run after all the test methods belonging to the classes inside the tag have run.
@BeforeClass: The annotated method will be run before the first test method in the current class is invoked.
@AfterClass: The annotated method will be run after all the test methods in the current class have been run.
@BeforeMethod: The annotated method will be run before each test method.
@AfterMethod: The annotated method will be run after each test method.
@Test: The annotated method is a part of a test case.

Install TestNG in IntellijIDEA 

 1. Select Help menu --> click on find action --> enter TestNG --> select TestNG from the listed plugins and install it.
2. After installation and restarting it, just verify if TestNG was needed successfully installed. Right click on your prooject and see if TestNG is dispalyed.
How to run Test Suite using TestNG

1. Create project let say "DemoProject".

2. Create package e.g. "com.company".

3. Create class files under the given project which are having number of test cases.

4. Right click on project and create new file "testng.xml" 

5. Open the testng.xml file and write the structure as follows:

 

<suite name="Test-Suite" >
<test name="Tools-QA">
<classes>
    <class name="<package name 1>.<class name 1"> />
    <class name="<package name 2>.<class name 2"> />
    <class name="<package name 3>.<class name 3"> />
    ...................

    ...................

</classes>
</test>
</suite>

6. Once create the file and mentioned the appropriate package name and class name then run this file as TestNG which will be executed all the test cases (class files) and execution will be done in the sequential manner. If one do not want to run second test then just comment it out and run the testng.xml file which will give you detail result of test suite.

7. After execution of this suite one can see the report in HTML format by clicking on "Export Test Result" icon on the top right corner of the left side console.

Will keep posting remaining.........

Select Language