How to run testng.xml from POM.xml (maven)

In this article i will talk about how to run testng.xml from maven’s POM.xml file. This is very useful feature of maven when we need to run multiple testng.xml files.

run testng.xml from pom.xml maven

The very first thing is, install maven in your eclipse IDE. Refer below article to know about how to install maven in eclipse ide.

How to download and Install Maven in Eclipse IDE?

Now, create a maven project.  Refer below article to understand how to create new project in eclipse IDE.

How to create Maven Project for Selenium in Eclipse IDE?

Now, write one sample test case in one of the folder created by maven, preferably test folder.  I have created below sample code –

package kdf1;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class Sample {
  
  @Test
  public void test(){
    System.out.println("Test Print");
    System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    
    driver.navigate().to("http://demowebshop.tricentis.com/");
    driver.manage().window().maximize();
    
    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
  }

}

Now, create testng.xml file for executing above test case. My testng.xml files looks like –

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Default suite">
  <test verbose="2" name="Default test">
    <classes>
      <class name="kdf1.Sample"/>
    </classes>
  </test> <!-- Default test -->
</suite> <!-- Default suite -->

Now, create a POM.xml file, add required dependencies. My POM.xml looks like –

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com</groupId>
  <artifactId>kdf1</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <dependencies>
  <dependency>
  <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>2.53.0</version>
  </dependency>
  
  <!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>6.9.9</version>
    <scope>test</scope>
</dependency>
  
  </dependencies>
    
</project>

Now, My job is to execute above given testng.xml file from above created POM.xml file via maven commands.

To achieve this, we need to use Suite XML files. Add below lines of code in POM.xml under <build> tags.

Make sure that you give the full testng.xml path.

<plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.20.1</version>
        <configuration>
          <suiteXmlFiles>
            <suiteXmlFile>testng.xml</suiteXmlFile>
          </suiteXmlFiles>
        </configuration>
      </plugin>
</plugins>

After adding above piece of code in to my POM.xml (under <build> tags), my POM.xml looks like –

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com</groupId>
  <artifactId>kdf1</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <dependencies>
  <dependency>
  <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>2.53.0</version>
  </dependency>
  
  <!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>6.9.9</version>
    <scope>test</scope>
</dependency>
  
  </dependencies>
  <build>
  <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.20.1</version>
        <configuration>
          <suiteXmlFiles>
            <suiteXmlFile>C:\Users\Prakash\workspace\kdf1\testng.xml</suiteXmlFile>
          </suiteXmlFiles>
        </configuration>
      </plugin>
</plugins>
  </build>
  
</project>

Thats it, you are done.

You are good to execute your testng.xml file from maven’s POM.xml. The main advantage of using this is we can execute multiple testng.xml files.

You can execute the project now by right clicking on project, Run As –> Maven Test  (another way to execute test case is from command prompt).

This was all about how to run testng.xml from pom.xml.

To know more about how to execute maven commands from command prompt, refer below link –

Maven Build Life Cycle – How to execute maven project

 

Hope this helps !!!!! Do provide your valuable comments !!!

How to Install Maven in Eclipse IDE ? – Build Tool for java

In this article i will talk about how to install maven in eclipse IDE. Maven is basically a build tool for java based projects.

There are two ways to install maven in eclipse IDE. First one is to install directly in Eclipse IDE via Eclipse MarketPlace / Install new software from help menu of Eclipse IDE & second one is, Install it on your machine manually & then configure the installation details in Eclipse IDE.

Let us talk about both methods.

1.  Install maven directly in eclipse IDE via eclipse marketplace or install new software from help menu

Follow below steps one by one

Open Eclipse, Go to Help Menu on Top right hand side & click on install new software.

Install maven 1

Add depository for downloading M2e as shown in below image.

Install maven 1

Then select work with as the current URL that you have added. It will show you the list of Maven Integration tools for Eclipse IDE. Select the desired one & click on next. Shown in below image

Install maven 1

Click on the next, below screen will show you the current installation items that you have selected.

Install maven 1

Now accept the Terms and conditions of license agreement & click on finish button so as to start with installation of maven plugin inside eclipse IDE. Shown in below image.

Install maven 1

Finally, You can see that software installation has begin. Shown in below image

Install maven 1

Once installation is finished, do restart your machine.

This is how we can install maven inside Eclipse IDE.

 

2. Another way to install maven is Install it in your machine & then configure it in Eclipse IDE.

Follow below steps to get the installation done using above method.

Download Maven files from : https://maven.apache.org/download.cgi

or click here apache-maven-3.5.2-bin.zip

Then Extract it to some folder. Let us say i am extracting it in my C:/ drive. So path of maven files is : C:\apache-maven-3.5.2

Now, Setup Environment Variables.

Go to start program, type “env“, in search result you can find option to edit environment variables. Click on it. Refer below image –

install maven

Once you click on it, System properties will open. Click on Environment variables. As shown in below image.

install maven

Now add below variables by clicking on new button for system variables.

JAVA_HOME=C:\Program Files\Java\jdk1.8.0_111
M2_HOME=C:\apache-maven-3.5.2
M2=%M2_HOME%\bin

Once above variable setup is done, Edit the “Path” variable. Enter below path at the end of current path (Do not modify anything other than this unless you are sure about it)

Path=;%M2%;%JAVA_HOME%\bin

install maven

Once this is done, click on OK. Now you are done with environment variable setup. Now you can verify if maven is installed correctly on your machine or not.

To check this, open command prompt & type below command.

mvn -version

Result of above command should show the currently installed maven version (This means maven is installed correctly) Refer below image.

install maven

Next part is now, to configure this installed maven in to your eclipse IDE.

Before we update anything in Eclipse IDE, first we need to modify setting.xml file from maven installation directory. Here we need to add the path of current maven repository at correct position. refer below image.

Location of settings.xml file: C:\apache-maven-3.5.2\conf\settings.xml

install maven

In the above image, the highlighted line need to be inserted at correct position, as shown above. Save the file.

Now let us update Eclipse IDE. To do this, Click on Window & go to preferences of your Eclipse IDE.

Go to maven –> Installations. Window will looks like below.

install maven

Now click on Add, and add the path of your current maven directory here & Click on OK. refer below image.

install maven

Now go to user Settings in the same menu & add path of your settings.xml file (Located in conf folder of your maven installation directory)

install maven

Click on OK.

That’s it, now done.

Clean your project & start with new maven project. You should be good to start with creation of maven project.

Refer below video for the same –

Refer below article to know about how to create new maven project.

How to create maven project in Eclipse IDE

 

Put your comments if you have any issues !!!! Thanks !!

 

 

 

 

Selenium Interview Questions and Answers – Part 2

On this page, you can find Selenium Interview questions and answers which may benefit to freshers to experienced professional. This is part 2 of this interview questions series.

1. How to Handle windows authentication popup using any third party tool .

Below are the steps to achieve this Using Autoit (Third Party Tool) –
Download and in Autoit editor write script through below command
ControlFocus(), ControlSet(), ControlClick()
Save file and Compile Script with your version and after that you get .exe file.
Java code for executing .exe file
Runtime.getRuntime().exec(\\Path)
It throws checked exception IOexception.

2. What are the different types of Exceptions in Selenium Webdriver?

Refer this post for detailed answer

3. What is StaleElementException?

StaleElementException occurs if I find an element, the DOM gets updated then I try to interact with the element.

4. Can we enter text without using sendKeys()?

Yes by using JavascriptExecutor

WebDriver driver = new FirefoxDriver();
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("document.getElementById("textbox_id").value='new value';);

5. How to find more than one web element in the list?

At times, we may come across elements of same type like multiple hyperlinks, images etc arranged in an ordered or unordered list. Thus, it makes absolute sense to deal with such elements by a single piece of code and this can be done using WebElement List.
Sample Code:

// Storing the list
List <WebElement> elementList = driver.findElements(By.xpath("//div[@id='example']//ul//li"));

// Fetching the size of the list 
int listSize = elementList.size(); 
for (int i=0; i<listSize; i++)
{
// Clicking on each service provider link 

serviceProviderLinks.get(i).click();

// Navigating back to the previous page that stores link to service providers 
driver.navigate().back();
}

6. What is the difference between driver.close() and driver.quit command?

close(): WebDriver’s close() method closes the web browser window that the user is currently working on or we can also say the window that is being currently accessed by the WebDriver. The command neither requires any parameter nor does is return any value.
quit(): Unlike close() method, quit() method closes down all the windows that the program has opened.
Same as close() method, the command neither requires any parameter nor does is return any value.

7. Difference between findElement/findElements ?

findElement () will return only single WebElement and if that element is not located or we use some wrong selector then it will throw NoSuchElement exception.
findElements() will return List of WebElements – for this we need to give locator in such a way that it can find multiple elements and will return you list of webelements then using List we can iterate and perform our operation.

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class findElementDemo {
public static void main(String[] args) throws Exception {
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://google.com");
Thread.sleep(5000);
List<WebElement> links=driver.findElements(By.xpath(".//*[@id='menu-top']/li")); System.out.println("Total element is "+links.size());
Iterator<WebElement> i1=links.iterator();
while(i1.hasNext)
WebElement ele1=i1.next();
String name=ele1.getText();
System.out.println("Elements name is "+name);
}
}
}

8. Difference between assert and verify in selenium Webdriver

When an “assert” fails, the test will be aborted. Assert is best used when the check value has to pass for the test to be able to continue to run log in.
Where if a “verify” fails, the test will continue executing and logging the failure.Verify is best used to check non critical things. Like the presence of a headline element.

9. How will you execute your login script using chrome browser from your editor using selenium?

System.setProperty("webdriver.chrome.driver","C:\\Users\\Public\\Documents\\Selenium\\chromedriver.exe"); 
WebDriver driver = new ChromeDriver();

10. Can we use multiple catch in try, how ?

Yes, we can use. Refer below Example –

public static void main(String args[]){ try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e)
{
System.out.println("common task completed");
}
 catch(ArithmeticException e) 
{
System.out.println("task1 is completed");
}
 catch(ArrayIndexOutOfBoundsException e)
 {
System.out.println("task 2 completed");
}
 System.out.println("rest of the code...");
}
}

Refer below posts for next interview questions –

Selenium Interview Questions and Answers – Part 2

Selenium Interview Question and Answers – Part 3

Selenium Interview Question and Answers – Part 4

Selenium Interview Question and Answers – Part 5

Different Types of Exceptions in Selenium WebDriver

During automation in Selenium WebDriver, we come across various exceptions & we need to deal with them. Below is the list of various exceptions occur in selenium webdriver.
In general, hierarchy of Exceptions in any language is shown in below image –
Exceptions in Selenium WebDriver

There are main three types of Exceptions in Selenium WebDriver –

  1. Checked Exceptions – These Exceptions can be handled during compile time. If they are not handled, it gives compile time error. Example- FileNotFoundException, IOException etc.
  2. Unchecked Exceptions – These exceptions can not be handled during compile time & they got caught at run time. Example – ArrayIndexOutOfBoundException.
  3. Error – Errors which can not be handled by using even try catch block. Example -Assertion Error.

Below are few common exceptions received during selenium scripting in java – selenium.

WebDriverException

WebDriver Exception comes when we try to perform any action on the non-existing driver.

WebDriver driver = new InternetExplorerDriver();
driver.get("http://google.com");
driver.close();
driver.quit();

NoAlertPresentException

When we try to perform an action i.e., either accept() or dismiss() which is not required at a required place; gives us this exception.

try{
driver.switchTo().alert().accept();
}
catch (NoAlertPresentException E){
E.printStackTrace();
}

NoSuchWindowException

When we try to switch to an window which is not present gives us this exception:

WebDriver driver = new InternetExplorerDriver();
driver.get("http://google.com");
driver.switchTo().window("Yup_Fail");
driver.close();

In the above snippet, line 3 throws us an exception, as we are trying to switch to an window that is not present.

NoSuchFrameException

Similar to Window exception, Frame exception mainly comes during switching between the frames.

WebDriver driver = new InternetExplorerDriver();
driver.get("http://google.com");
driver.switchTo().frame("F_fail");
driver.close();

In the above snippet, line 3 throws us an exception, as we are trying to switch to an frame that is not present.

NoSuchElementException

This exception is thrown when we WebDriver doesn’t find the web-element in the DOM.

WebDriver driver = new InternetExplorerDriver();
driver.get("http://google.com");
driver.findElement(By.name("fake")).click();

TimeoutException

Thrown when a command does not complete in enough time.

StaleElementException

StaleElementException occurs if I find an element, the DOM gets updated then I try to interact with the element.

If Javascript updates the page between the findElement call and the click call then I’ll get a StaleElementException. It is not uncommon for this to occur on modern web pages. It will not happen consistently however. The timing has to be just right for this bug to occur.

So how do I handle it? I use the following click method:

public boolean retryingFindClick(By by) { boolean result = false;
int attempts = 0;
while(attempts < 2) {
try {
driver.findElement(by).click();
result = true;
break;
} catch(StaleElementException e) {
}
attempts++;
}
return result;
}

So, these the common exceptions which occur during automation which i tried to cover. Hope this helps !!!!

Data Driven Framework in Selenium WebDriver

Before we start with data driven framework, let us understand few important things.

Why not to hard code in Test Automation Framework?
–>Let us take an example of testing web application. In actual, you may need to run test cases in various environments like Unit Testing, System Testing, System Integration Testing, UAT & can be in Production. So for all these regions, URL will be different, username and password can be different. So if you are hard coding these things, you need to change them for each environment. So its not good practice to hard code the things which are used at multiple places.

Now, to Skip hard coding, what to do?
1. Use properties file
2. Use Excel file

 

Refer below video tutorials for the same.

Data Driven Testing – Part 1

Data Driven Testing – Part 2

Data Driven Testing – Part 3

Data Driven Framework:
It is nothing but to execute one test case with multiple set of data, with multiple conditions. When you wanted to execute similar flow (let us say account opening procedure) with various data combinations, it is not good idea to create separate test case for each data set, so this is how data driven frameworks came in to picture.

Components of Data Driven Framework:

Create a folder Structure for your framework, refer below screenshot in which i have shown a sample folder structure for data driven framework.

Data Driven framework Testing in Selenium - folder structure - www.automationtalks.com
1. Package for Page Object –>
This package will contain all page object. For each page there should be one class containing all objects / web-elements from that page. This helps to keep changing web-element away from our actual test cases. This is to achieve Page Object Model (POM) in our Test Automation Framework.

2. Package for Properties file –>
This package will contain all properties file to store data like URL, credentials & other. So that any changes in dynamic parameters like URL, username, passwords need not to change the values in code. Just change in these properties file, should update it in all test cases.

3. Package to keep Test Data –>
This package is to keep test data of data driven testing. This data can be kept in excel file format. Apache POI / JXL api can be used to read this data & use it for test cases during execution. Test data can also be kept in notepad, any database. But preferred one is Excel.

4. Package to write actual Test Cases –>
In a framework, code for actual test cases should be isolated from other commonly used methods & files. So this package is to write the actual test cases. Other classes from other packages can be called while writing test cases.

5. Utilities used for framework –>
As i said above, in framework, only actual test cases should be kept in one package & rest other common methods should be kept in another one. This utilities package will contain all common methods that are required for Test Automation Framework. For Example – Take Screenshot, logging, common skeleton to launch driver, listeners, reporters etc.

6. Create one folder to keep all jar files (If you are not using Maven in your project)

7. Create one folder to store log information (with the help of log4j & listeners)

Now, refer the below code from each of the module for complete Data Driven Framework

Step 1: Create the folder structure as shown above.
Step2: Create config.properties file in propFiles package, refer below properties file

URL=http://demowebshop.tricentis.com/
browser=chrome
#username=
#password=
filepath=C://Users//Prakash//workspace//ddf//src//com//demowebshop//testData//LoginData.xlsx

Step3: Create Log4j.properties file under src folder which is used for logging information. Refer below code for log4j.properties

// Here we have defined root logger
log4j.rootLogger=ALL,CONSOLE,R

// Here we define the appender
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.R=org.apache.log4j.RollingFileAppender

log4j.appender.dest1=org.apache.log4j.RollingFileAppender
log4j.appender.dest1.maxFileSize=5000KB
log4j.appender.dest1.maxBackupIndex=3

// Here we define log file location
log4j.appender.R.File=./log/testlog.log

// Here we define the layout and pattern
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern= %5p [%t] (%F:%L)- %m%n
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d - %c -%p - %m%n

Step4: Identify and write page objects which you require for your test case. This will achieve Page Object Model (POM). For my sample example, i have identified objects for login test case. Refer below objects.
HomePageObjects:

package com.demowebshop.pageObjects;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class HomePage {
  
  public static String  LoginLinkXpath = "//a[@class='ico-login']";
  
  public static WebElement  LoginLinkWebElement(WebDriver driver){
    return driver.findElement(By.xpath(LoginLinkXpath));
    
  }

}

LoginPageObject:

package com.demowebshop.pageObjects;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class LoginPage {
  
  public static String  EmailFieldXpath = "//input[@id='Email']";
  public static String  PasswordFieldXpath = "//input[@id='Password']";
  public static String  LoginButtonXpath = "//input[@class='button-1 login-button']";


  
  public static WebElement  EmailFieldWebElement(WebDriver driver){
    return driver.findElement(By.xpath(EmailFieldXpath));	
  }
  public static WebElement  PasswordFieldWebElement(WebDriver driver){
    return driver.findElement(By.xpath(PasswordFieldXpath));	
  }
  public static WebElement  LoginButtonWebElement(WebDriver driver){
    return driver.findElement(By.xpath(LoginButtonXpath));	
  }

}

Step5: Now, its time to write utilities.

First one is to read properties file. Data stored in properties file like URL, browser & other need to be used in test cases. So below class will help to read properties file.

package com.demowebshop.utilities;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

public class ReadPropertiesFile {
  
  Properties prop = new Properties();
  String filePath = "C://Users//Prakash//workspace//ddf//src//com//demowebshop//propFiles//config.properties";
  
  
  public String ReadPropertiesFileByKey(String key) throws FileNotFoundException{
    
    File file = new File(filePath);
    FileInputStream fis = new FileInputStream(file);	
    try {
      prop.load(fis);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return prop.getProperty(key);
    
    
  }

}

Now, once we get browser value from properties file, select the browser using below class

package com.demowebshop.utilities;

import org.apache.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class SelectBrowser {

  Logger log = Logger.getLogger("BrowserSelection");

  public WebDriver selectBrowser() throws Exception {

    ReadPropertiesFile prop = new ReadPropertiesFile();
    WebDriver driver = null;

    String browser = prop.ReadPropertiesFileByKey("browser");

    while (browser == null) {
      log.fatal("Browser is not specified in Configuration file. Terminating process !!!");
      System.exit(0);
    }
    if (browser.equalsIgnoreCase("firefox")) {
      driver = new FirefoxDriver();
      log.info("Browser selected for testing is :  Mozilla Firefox");
    } else if (browser.equalsIgnoreCase("chrome")) {
      System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
      driver = new ChromeDriver();
      log.info("Browser selected for testing is :  Google Chrome");

    } else if (browser.equalsIgnoreCase("ie")) {
      System.setProperty("webdriver.ie.driver", "C:\\IEDriverServer.exe");
      driver = new InternetExplorerDriver();
      log.info("Browser selected for testing is :  Internet Explorer");

    } else {
      log.fatal("Selected browser value should be either firefox or chrome or ie --> Update in Configuration file is required");

      System.exit(0);
    }
    return driver;
  }
}

Since we are using data driven testing, our test data is stored in excel file. This excel file need to read & process the test cases based on test data. Use below class to read excel file –

package com.demowebshop.utilities;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.log4testng.Logger;

public class ExcelReader {
  
  static ReadPropertiesFile prop = new ReadPropertiesFile();
  Logger log = Logger.getLogger(ExcelReader.class);

    static FileInputStream fis = null;

  public  FileInputStream getFileInputStream() throws FileNotFoundException{
    
     String filepath = prop.ReadPropertiesFileByKey("filepath");
    File srcfile = new File(filepath);
    try {
      fis = new FileInputStream(srcfile);
    } catch (FileNotFoundException e) {

      log.fatal("TestData File is not found. terminating process !!! Check Configuration file for file path of TestData file");
      System.exit(0);	
    }
    return fis;		
  }
  
  
  public  Object[][] getExceData() throws Exception{
    fis = getFileInputStream();
    
    XSSFWorkbook wb = new XSSFWorkbook(fis);
    XSSFSheet sheet = wb.getSheetAt(0);
    
    int TotalNumberOfRows = (sheet.getLastRowNum()+1);
    int TotalNumberOfCols =2;
    
    String[][] arrayExcelData = new String[TotalNumberOfRows][TotalNumberOfCols];
    
    for (int i = 0; i<TotalNumberOfRows; i++){
        for (int j=0; j<TotalNumberOfCols; j++){
          XSSFRow row = sheet.getRow(i);

      //		String cellData = row.getCell(j).toString();
          arrayExcelData[i][j] = row.getCell(j).toString();
        }
    }
    wb.close();
    return arrayExcelData;
    
  }
    

}

Its time to create a common skeleton (to use driver from another class, which will be common for @BeforeMethod and @AfterMethod annotation. Refer below code –

package com.demowebshop.utilities;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;

public class BaseTest {

  SelectBrowser select = new SelectBrowser();
  ReadPropertiesFile prop = new ReadPropertiesFile();
  
  protected WebDriver driver = null;
  
  @BeforeMethod
  public void launchBrowser() throws Exception{
      String url = prop.ReadPropertiesFileByKey("URL");
    driver = select.selectBrowser();
    driver.navigate().to(url);
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    driver.manage().window().maximize();
  }
  
  @AfterMethod
  public void closeBrowser(){
    
    driver.close();
    driver.quit();
    
  }

}

Once all this is done, Its time to write actual test. Use dataprovide annotation to pass the data which we read it from excel reader.
I am using demowebshop.tricentis.com & its login functionality to demonstrate.
Refer below code  –

package com.demowebshop.Tests;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import com.demowebshop.pageObjects.HomePage;
import com.demowebshop.pageObjects.LoginPage;
import com.demowebshop.utilities.BaseTest;
import com.demowebshop.utilities.ExcelReader;

public class LoginTest extends BaseTest{

  @Test(dataProvider = "TestData1")
  public void LoginTestCase( String username, String password){
    System.out.println(username);
    System.out.println(password);
    HomePage.LoginLinkWebElement(driver).click();
    LoginPage.EmailFieldWebElement(driver).sendKeys(username);
    LoginPage.PasswordFieldWebElement(driver).sendKeys(password);
    System.out.println(driver.getTitle());
  }

  @DataProvider(name = "TestData1")
  public Object[][] LoginTestData() throws Exception{
    ExcelReader ER = new ExcelReader();
    return ER.getExceData();
  }

}

Once this is done, Update your test data file (for Data Driven Framework) with your username and passwords, as shown below –

Data Driven Testing in Selenium - test data sheet - www.automationtalks.com

 

Now, you are good to run Test. Right click on your actual test case, Run it as TestNG Test.

You should good results.

To learn how the same can be achieved using Map and HashMap, refer –

How to use Map (HashMap) with TestNG DataProvider in Data Driven Testing?

Refer below topics related to automation frameworks –

Automation Frameworks –

This is all about Data Driven Framework. Hope This helps !!!

How to refresh browser in Selenium WebDriver using different methods

In this article, we will talk about how can we refresh browser using various methods.

Some time it is required to refresh the webpage to accomplish the testing objective. Let us see how this can be achieved.

Method1: Using navigate().refresh() method

Method2: Using JavaScriptExecutor

Method3: Using Actions Class

Mehtod4: Get the current URL & navigate using get() method

Method5: Get the current URL & navigate using navigate().to() method

Look at the below example –
package basicsOfSelenium;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class RefreshBrowserInDiffWays {

 public static void main(String[] args) {

  WebDriver driver = new FirefoxDriver();
  driver.navigate().to("https://www.google.co.in");
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  
  // Method1:  Using navigate().refresh() method
  driver.navigate().refresh();
  
  //Method2: Using JavaScriptExecutor
  JavascriptExecutor js = (JavascriptExecutor)driver;
  js.executeScript("history.go(0)");
  
  //Method3: Using Actions Class
  Actions actions = new Actions(driver);
  actions.keyDown(Keys.CONTROL).sendKeys(Keys.F5).perform();
  
  //Mehtod4: Get the current URL & navigate using get() method
  driver.get(driver.getCurrentUrl());
  
  //Method5: Get the current URL & navigate using navigate().to() method
  driver.navigate().to(driver.getCurrentUrl());
  
 }

}

Hope this helps!!!!

How to handle Authentication Required popup using AutoIT?

While browsing some websites, Authentication required popup comes asking username and password. Observe below snap.

Now, this can be handled using either robot class or by using AutoIT script.
Let us see how this Authentication Required popup is handled using AutoIT script.
Script used to handle this Authentication popup is as below –
WinWaitActive(“Authentication Required”,””,”10″)

 

If WinExists(“Authentication Required”) Then

 

Send(“username{TAB}”)

 

Send(“Password{Enter}”)

 

EndIf
Add this script in SciTE editor. Save the file with some name by .au3 extension.
Now compile the script by right clicking on it, with respective version.
Once compilation is successful, .exe file will be created with same name.
Now, we can use this .exe file & run this via our selenium Webdriver script.
                        Runtime.getRuntime().exec(“C:/Users/Prakash/Desktop/TestScript.exe”);
That’s, all, this is how we can handle Authentication Required Popup using AutoIT

How to upload file in selenium using AutoIT

In earlier articles, we saw that, we can upload the file using sendKeys() method or by using robot class.
Refer below articles for this.

Upload file in selenium using sendkeys() method.

Upload file in selenium using robot class

Now, in case both of the above methods won’t work, then we have to use AutoIT tool (which a third-party tool used to handle window popups). Let’s talk how this can be done.
AutoIt v3 is a freeware BASIC-like scripting language designed for automating Windows GUI and general scripting. It uses a combination of simulated keystrokes, mouse movement and window/control manipulation in order to automate tasks.
This method is for handling the Windows File Upload dialog, which cannot be handled using Selenium. Please follow below steps:
         
           1.       Download AutoIT setup file from here (https://www.autoitscript.com/site/autoit/downloads/)
      
           2.       Open Au3Info.exe for which helps to find window information details.
           
          3.       Open SciTE Script Editor.
            Script used to upload the file is as below. Write the script below in script editor.
               ControlFocus(“File Upload”,””,”Edit1″)

               ControlSetText(“File Upload”,””,”Edit1″,”C:UsersPrakashDesktopTOSCA tutorial.pptx”)

               ControlClick(“File Upload”,””,”Button1″)
              We can get Title and control id from application Au3Info.exe. Just Drag and drop the finder tool at required position. 

              In this script Control Focus is used to focus on the field where we enter the file to be uploaded path details. Note that Control id is the combination of Class and Instance.
     
        Syntax –  ControlFocus(“title”,”text”,”Control id”)
                                                       
                          ControlSetText is used to write the text (file path of the file to be uploaded)
                          Syntax – ControlSetText(“title”,”text”,”Control id”,”file path”)
 
                          ControlClick is used to click on the button.
                           Syntax – ControlClick(“title”,”text”,”Control id”)
 
              2.       Save the Script with some name with .au3 extension. 
 
              3.       Then right click on it, click on Compile.
               4.       Then Double click on the same file.
              5.       Now you will see the .exe file with same name is generated.
                   We are going to use this .exe file in our java – selenium program (to upload the file using AutoIT).
        
             6.       Use below piece of code for executing the .exe file created above
                 
               Runtime.getRuntime().exec(“C:UsersPrakashDesktopTestScript.exe”);
          
          Refer below example –

package basicsOfSelenium;

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

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class AutoIT {

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub

WebDriver driver = new FirefoxDriver();
driver.navigate().to("http://www.tinyupload.com/");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();

// Click on Browse Button
driver.findElement(By.xpath("html/body/table/tbody/tr[4]/td/table/tbody/tr/td[2]/form/table/tbody/tr[2]/td[1]/input[2]")).click();

//After pop-up open, below script is used to upload the file
Runtime.getRuntime().exec("C:UsersPrakashDesktopTestScript.exe");

}
  
Hope this helps !!!!