Monday, June 17, 2013

Data Driven Testing using Selenium

Example: Load and return data into Excel file.

TestcaseLogin.java
package datadriver;

public class TestCaseLogin {
      private String userName;
      private String password;
      private String status;
     
      public String getUserName() {
            return userName;
      }
      public void setUserName(String userName) {
            this.userName = userName;
      }
      public String getPassword() {
            return password;
      }
      public void setPassword(String password) {
            this.password = password;
      }
      public String getStatus() {
            return status;
      }
      public void setStatus(String status) {
            this.status = status;
      }
     
     
     
}

ExcelSheetDriver.java
package datadriver;

import java.io.IOException;

import com.sun.org.apache.xalan.internal.xsltc.runtime.Hashtable;

import jxl.Cell;
import jxl.JXLException;
import jxl.LabelCell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.CellFormat;
import jxl.format.Colour;
import jxl.format.Font;
import jxl.format.Format;
import jxl.format.Orientation;
import jxl.format.Pattern;
import jxl.format.VerticalAlignment;
import jxl.read.biff.BiffException;
import jxl.read.biff.File;
import jxl.write.Label;
import jxl.write.WritableCell;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

public class ExcelSheetDriver {
      final static int COLUMN_COUNT = 3;
      final static int ROW =1;
      final static int COL =3;
      static Sheet wrksheet;
      static Workbook wrkbook =null;
      static Hashtable dict= new Hashtable();
      static final int USERNAM_COLUMN = 0;
      static final int PASSWORD_COLUMN = 1;
      static final int STATUS_COLUMN = 2;
      //Create a Constructor
      public ExcelSheetDriver(String ExcelSheetPath) throws BiffException, IOException
      {
            //Initialize
            wrkbook = Workbook.getWorkbook(new java.io.File(ExcelSheetPath));
           
            wrksheet = wrkbook.getSheet("Login");
      }

      //Returns the Number of Rows
      public static int RowCount()
      {
            return wrksheet.getRows();
      }

      //Returns the Cell value by taking row and Column values as argument
      public static String ReadCell(int column,int row)
      {
            Cell cell = wrksheet.getCell(column,row);
            if (cell != null) {
                  return cell.getContents();
            }
            return "";
      }
     
      public static TestCaseLogin[] getData() {
            // Skip header
            TestCaseLogin[] results = new TestCaseLogin[wrksheet.getRows() - 1];
            System.out.println("Num of tesr cases: " + results.length);
            TestCaseLogin testCaseLogin = null;
            // Iterate through all the columns in the Excel sheet and store the
            // value in Hashtable
            for (int row = 1; row < wrksheet.getRows(); row++) {
                                    testCaseLogin = new TestCaseLogin();
                  testCaseLogin.setUserName(ReadCell(USERNAM_COLUMN, row));
                  testCaseLogin.setPassword(ReadCell(PASSWORD_COLUMN, row));
                  testCaseLogin.setStatus(ReadCell(STATUS_COLUMN, row));
                  results[row - 1] = testCaseLogin;
            }
            return results;
      }
     
      //Create Column Dictionary to hold all the Column Names
      public static void ColumnDictionary()
      {
            //Iterate through all the columns in the Excel sheet and store the value in Hashtable
            for (int row = 0; row < wrksheet.getRows(); row++) {
                  for(int col=0;col < COLUMN_COUNT; col++)
                  {
                        dict.put(ReadCell(col,row), col);
                  }
            }

      }

      //Read Column Names
      public static int GetCell(String colName)
      {
            try {
                  int value;
                  value = ((Integer) dict.get(colName)).intValue();
                  return value;
            } catch (NullPointerException e) {
                  return (0);

            }
      }
      //Update to Excel file
      public static void updateToExcel (TestCaseLogin[] data, String tempplate) throws RowsExceededException, JXLException, IOException {
            WritableWorkbook writableWorkbook =  Workbook.createWorkbook(new java.io.File(tempplate), wrkbook);
            WritableSheet writableSheet = writableWorkbook.getSheet("Login");
            WritableCell cell = null;
            LabelCell labelCell = null;
           
            Label l = null;
           
            TestCaseLogin testCaseLogin = null;
            for(int row = 1; row < wrksheet.getRows(); row++){
                  testCaseLogin = data[row-1];
                 
                  l = new Label (STATUS_COLUMN, row, testCaseLogin.getStatus());

                  writableSheet.addCell(l);

            }
           
            writableWorkbook.write();
            writableWorkbook.close();
                 
           
      }
     
}


ReadDataJunitTest.java
package datadriver;

import java.awt.List;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import jxl.JXLException;
import jxl.read.biff.BiffException;
import jxl.write.biff.RowsExceededException;

import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
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 com.sun.org.apache.bcel.internal.generic.Select;

public class ReadDataJunitTest {
      // Global initialization of Variables
      static ExcelSheetDriver xlsUtil;
      WebDriver driver = new FirefoxDriver();
      TestCaseLogin[] data = null;
      boolean flag =false;
      // Constructor to initialze Excel for Data source
      public ReadDataJunitTest() throws BiffException, IOException {
           
            xlsUtil = new ExcelSheetDriver(
                        "D:\\New folder\\seleniumdriver\\data.xls");
            xlsUtil.ColumnDictionary();
      }

      @Before
      public void EnvironmentalSetup() {
            data = ExcelSheetDriver.getData();
            driver.get("http://sgndtr8grzg5.corp.capgemini.com/LMS/index.php");
      }

      @Test
      public void GmailLoginPage() throws InterruptedException {
            GmailLoginPage(data);
      }
     

      public void GmailLoginPage(TestCaseLogin[] testCaseLogins)
                  throws InterruptedException {

            WebElement userName = null;
            WebElement password = null;
           
            WebElement signin = null;
            WebElement modalpopup = null;
            WebElement signout = null;
            for (TestCaseLogin testCaseLogin : data) {

                  if (testCaseLogin == null) {
                        continue;
                  }
                 
                  //Enter UserName
                  userName = (new WebDriverWait(driver, 15)).until(ExpectedConditions
                              .presenceOfElementLocated(By.name("cookie_user_name")));

                  userName.clear();
                  userName.sendKeys(testCaseLogin.getUserName());

                  // Enter Password
                  password = driver.findElement(By.name("cookie_user_password"));
                  password.clear();
                  password.sendKeys(testCaseLogin.getPassword());

                  System.out.println("Login user: " + testCaseLogin.getUserName());
                 
                 
                 
                  driver.findElement(By.name("slctSSOService")).sendKeys("LMS");
           
                 
                  // Click on the Sign In Button
                  signin = driver.findElement(By.name("Imagefield"));
                  signin.click();
                 
                  //Alert
                  WebDriverWait wait = new WebDriverWait(driver, 5);
                  // Wait for 10 seconds and check if Alert present
                  wait.withTimeout(10, TimeUnit.MILLISECONDS);
                  try {
                        Alert alert = driver.switchTo().alert();
                        if (alert != null) {
                              alert.accept();
                              System.out.println("Login Failed");
                              testCaseLogin.setStatus("FAILED");
                              driver.switchTo().defaultContent();
                              continue;
                        }
                  } catch (NoAlertPresentException e) {
                        // Login successfully, no alert presents
                  }
           
                  // Click on Logout link
                  try {

                        signout = (new WebDriverWait(driver, 15))
                                    .until(ExpectedConditions.presenceOfElementLocated(By
                                                .linkText("Logout")));
                        System.out.println("Login successfully");
                        Thread.sleep(10000);
                  } catch (Exception e) {
                        System.out.println("Login Failed");
                        testCaseLogin.setStatus("FAILED");
                        continue;
                  }
                  testCaseLogin.setStatus("PASS");
                  System.out.println("Logout user: " + testCaseLogin.getUserName());
                  System.out.println("Signout tag" + signout.toString());
                  signout.click();
                  System.out.println("Logout successfully");
            }
            resultLogin(data);
            driver.close();

      }

      public void resultLogin(TestCaseLogin[] data){
//          for (TestCaseLogin testCaseLogin : data) {
                  String template = "D:\\New folder\\seleniumdriver\\data.xls";
                  try {
                        xlsUtil.updateToExcel(data, template);
                  } catch (RowsExceededException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                  } catch (JXLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                  } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                  }
//          }
      }
     
//    @Test
      public void testWriteData () {
            TestCaseLogin[] testCaseLogins = new TestCaseLogin[4];
            TestCaseLogin testCase = new TestCaseLogin();
            testCase.setStatus("PASS");
            testCaseLogins[0] = testCase;
            testCase = new TestCaseLogin();
            testCase.setStatus("Failed");
            testCaseLogins[1] = testCase;
            testCase.setStatus("Failed");
            testCaseLogins[2] = testCase;
            testCase = new TestCaseLogin();
            testCase.setStatus("Failed");
            testCaseLogins[3] = testCase;
           
            resultLogin(testCaseLogins);
           
      }
}
  

Result as below:


4 comments:

  1. Hi Hoa,

    you may be interested in SeLite. It's a framework for Selenium that allows your tests to access (read and write to) a test database (separate from the database of the tested application).

    You seem to use Selenium WebDriver, while SeLite is for Selenium IDE. It adds a new dimension to existing flexibility and convenience of IDE.

    See https://code.google.com/p/selite/wiki/ProjectHome.

    ReplyDelete
  2. Good.. Keep posting more...

    Visit selenium easy for complete webdriver tutorials with sample frameworks and examples
    https://seleniumeasy.com

    ReplyDelete
  3. https://allinoneissues.blogspot.com/2013/07/hadoop-admin-interview-question-and.html?showComment=1631532438719#c5360193906077814626

    ReplyDelete
  4. Your blog has wonderful information regarding Guidewire Services, I also have some valuable information regarding the Guidewire Testing in USA, Canada hopefully, this will be very helpful for you.

    ReplyDelete