Testing With Selenium WebDriver (72 Blogs) Become a Certified Professional
AWS Global Infrastructure

Software Testing

Topics Covered
  • Testing With Selenium WebDriver (62 Blogs)
SEE MORE

How to Create a Selenium Maven Project in Eclipse IDE?

Last updated on Apr 19,2024 68.1K Views

2 / 2 Blog from Selenium Projects

Selenium is one of the most widely used automation tools for testing a web application. It has out thrown all the traditional ways of testing. The advancement in the field of testing has also increased the number of people taking up the Selenium online course. So, this article on creating a Selenium Maven Project with Eclipse will help you understand how easy it is to run a test case on the Eclipse IDE.

In this how to create Maven Project in Eclipse for Selenium blog, we’ll discuss the following topics.

Ever wondered why Selenium has a great value when it comes to testing a web application? What is Selenium? What makes it unique? Let’s go ahead and unveil the various features which are responsible for the outstanding demand of this framework.

What is Selenium? What are its features?

Selenium is a top-tier technology which helps in testing a web application and automating the processes associated with the same.

Selenium -Selenium Maven with EclipseThe features of Selenium comprises of the following:

  • Selenium is an open source portable framework used to test web applications.
  • Test cases can be written in different programming languages like Java, Python, Ruby etc., but the most commonly used among these would be Java because of its user-friendly behavior.
  • The test cases can run across different browsers like Chrome, Explorer, Safari, Opera and so on.
  • Selenium also supports cross browsing. Cross-browsing refers to the process where the test cases can run across different platforms simultaneously.
  • It has a set of commands called Selenese which holds the sequence of all the Selenium commands.
  • Elements can be easily located on a web page using the element locators.
  • Selenium tests only web applications. It cannot perform actions on any desktop or mobile applications.

What is Maven?

Maven - Selenium Maven with Eclipse - EdurekaMaven is a build automation tool. It is basically a software project management and comprehension tool which can manage the project’s build, reporting, and documentation. 

Maven is a Yiddish word which means “accumulator of knowledge”. It was first started by the Apache Software Foundation (ASF) in the year 2002 for the Jakarta Alexandria project. The features of Maven include:

  • Maven is a powerful project management tool that is based on the POM (project object model). 
  • It provides a simple project set up by giving a boilerplate for projects or modules.
  • It is consistent across different projects.
  • Also has the ability to work with multiple projects at the same time.
  • Able to build any number of projects into its predefined output types such as a JAR, WAR, without any scripting in most cases.

What is the Eclipse IDE?

Eclipse - Selenium Maven with Eclipse - Edureka

Eclipse is an integrated development environment (IDE) for developing applications in Java and other languages such as C, C++, Python, Perl, Ruby etc. This platform can be used to develop rich client applications, IDEs, and other tools.

  • The platform which provides the nub to the Eclipse IDE is basically composed of plugins.
  • It is written mostly in Java and the primary use is for developing Java applications, but it may also be used to develop applications in other programming languages. 
  • Talking about the license of the tool, it is an open source software which can be run across different browsers.
  • Eclipse Public License (EPL) is the fundamental license under which Eclipse projects are released.
  • The plug-in framework allows the Eclipse Platform to work with typesetting languages such as LaTeX, and networking applications such as telnet and DBMS.

Check out this video on Selenium where our Selenium testing expert is explaining how to install Selenium on your system.

Download & Install Selenium | Selenium WebDriver Setup | Selenium Installation Guide | Edureka

This Edureka video on How to Install Selenium will talk about Java Installation, Eclipse Installation followed by Installing Selenium on your system.

Why do we use Eclipse to run the Selenium Maven project? 

We consider using the Eclipse platform to work with Selenium Maven because Eclipse IDE is the most popular editor to develop Java applications and it is free and easy to understand and has more community support.

  • Eclipse provides a user-friendly environment.
  • This IDE will cost you less time and effort.
  • It supports many languages other than just Java.
  • Framework integration like Junit and TestNG and other plugins can be done easily.
  • Since Eclipse tools are open source, it is quickly updated with the latest technology that can be integrated into existing code.
  • Navigating through a web page is made easy.
  • Auto-completion is one of the best features, you don’t have to remember all the functions while working on Eclipse.
  • Helps in refactoring, i.e. it helps in restructuring the existing code by changing the factors without changing its external behavior.
  • Error debugging is easy, you can easily navigate to an error line.
  • All files can be viewed and managed on the same screen.
  • Better organizing of the imports.
  • Downloading requires packages at ease.

Learn more about Automation and its applications from the Automation Testing Certification.

Selenium Maven Project Structure

The Selenium Maven project has a simplified view of how the programs reside in the package being created. Maven project has a pom.xml file and a directory structure:

└───maven-project
    ├───pom.xml
    ├───README.txt
    ├───NOTICE.txt
    ├───LICENSE.txt
    └───src
        ├───main
        │   ├───java
        │   ├───resources
        │   └───filters
        
        ├───test
        │   ├───java
        │   ├───resources
        │   └───filters
        ├───it
        ├───site
        └───assembly

Let’s take a look at the way the Selenium Maven project is branched.

Selenium-Maven-with-eclipseLet’s take a look at the fields that are present in the first project, EdurekaSeleniumProject.

Selenium-maven-with-eclipse-project-structure

Now, let me brief about the directories & files present in the Selenium Maven project.

  • pom.xml
  • src and target
  • src/main/java
  • src/test/java
  • Maven dependencies

Let’s analyze each of these folders in detail.

  • At the top level, a descriptive of the project, i.e. a pom.xml file is present. This file holds the maven dependencies of a particular package. In addition, there are some textual documents meant for the user to read immediately on receiving the source file: README.txt, LICENSE.txt, etc.
  • This pom.xml file is the core of a project’s configuration in Maven. It is a single configuration file that contains all the information required to build a project in just the way you want. The Project Object Model is huge and can be daunting in its complexity, but it is not necessary to understand all of the intricacies just yet to use it effectively. The structure of this pom.xml file is something like this.

<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>Automation</groupId>
<artifactId>EdurekaSeleniumProject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>AutomationProject</name>
<description>SeleniumAutomation</description>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependency>
//any dependencies 
</dependency>

  • Basically, there are just two subdirectories of this structure: src and target.
  • The target directory is used to house all the output of the build. It even holds the compilation results and the test reports.
  • The src directory holds all of the source material for building the project, its site and so on. It contains a subdirectory for each type: main for the main build artifact, test for the test codes and resources, for any kind of additional resources required to execute the project.
  • Dependencies: Maven encourages the use of a central repository of JARs and other dependencies. It comes with a mechanism that your project’s clients can use to download any JARs required for building the project from a central repository. This allows users of Maven to reuse the JARs across projects and encourages communication between projects to ensure that backward compatibility issues are properly dealt with.

How to Create Maven Project in Eclipse for Selenium?

Let’s consider this particular project where we shall try automating the process of booking a flight. Let’s take a look at how it’s done using the Selenium Maven project.

Let’s divide the process into the relevant pages.

  • We’ll start with initializing the browser driver and then log in to the web page
  • Find the flight according to the user requirements
  • Select a flight and book it
  • Capture a screenshot of the confirmation page

Go to File-> Go to New-> Others -> Maven Project to create a new Java project.

Creating new project - Selenium Maven - Edureka

Step 2: Add the dependencies to pom.xml file

Dependencies - Selenium- Maven- with Eclipse- Edureka

Step 3: Create the packages

Create the packages under the src/main/java folder and the src/test/java folder and start writing the piece of code.

 

Packages - Selenium- Maven- with - Eclipse- EdurekaStep 4: Write the code to run the test cases

BrowserFactory()

First, let’s set the browser driver and start the process by creating a public class called BrowserFactory() under which we will instantiate the browser instances. Let us consider ChromeDriver as our browser driver for this project because it is easy to inspect the web page using Chrome.

  • Instantiate the ChromeDriver using ChromeOptions options = new ChromeOptions() command.
  • Decrease/limit the page load timeout of execution using options.setPageLoadStrategy(PageLoadStrategy.NONE)
  • Set the system property to the name of the webdriver and the path where the driver is present using this command: System.setProperty(“webdriver.chrome.driver”, “D:chromedriver.exe”)
  • Next, to maximize the web page, we use this command: driver.manage().window().maximize()
  • Add in some commands that help in the easy execution of the process that deletes the cookies, driver.manage().deleteAllCookies();
  • Add implicit waits where you want the execution to wait for a certain time, driver.manage().timeouts().implicitlyWait(45, TimeUnit.SECONDS);
  • Add the page load wait that helps in limiting the wait for loading a particular web page, driver.manage().timeouts().pageLoadTimeout(45, TimeUnit.SECONDS);
  •  The same procedure follows for the other browser drivers like FireFox, IE as well.

package com.edureka.frameworkPackage;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.PageLoadStrategy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class BrowserFactory {

public static WebDriver driver;

public BrowserFactory(){

}

public static WebDriver getDriver(){
if(driver==null){
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-notifications");
options.setPageLoadStrategy(PageLoadStrategy.NONE);
System.setProperty("webdriver.chrome.driver", "D:chromedriver.exe");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
<a name="Login Page"</a>driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(45, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(45, TimeUnit.SECONDS);
}
return driver;
}

public static WebDriver getDriver(String browserName){
if(driver==null){
if(browserName.equalsIgnoreCase("firefox")){
System.setProperty("webdriver.gecko.driver", ""D:Softwaresjarsgeckodriver-v0.23.0-win64geckodriver.exe"");
driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(45, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(45, TimeUnit.SECONDS);
}else if(browserName.equalsIgnoreCase("chrome")){
System.out.println("in chrome");
System.setProperty("webdriver.chrome.driver", "D:chromedriver.exe");
driver=new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(45, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(45, TimeUnit.SECONDS);
}else if(browserName.equalsIgnoreCase("IE")){
System.setProperty("webdriver.ie.driver", ""D:SoftwaresjarsIEDriverServer_Win32_3.14.0IEDriverServer.exe"");
driver=new InternetExplorerDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(45, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(45, TimeUnit.SECONDS);
}
}
return driver;
}
}

 

Next, we’ll take a look at how we can log in to a web page.

Login Page

  • Create a class LoginPage and initiate the instance of a variable to the driver.
  • Annotations like FindBy and CacheLookup are used to find the element on a webpage.
  • @FindBy helps to specify the object location strategy for a web element.
  • @CacheLookup helps us know when to cache a web element and when not to, and declares the web element to be searched.
  • So, basically in this project, we will use the web element and create an object of the same, and find the element by using the element locators in Selenium.
  • Create a function loginWordPress() and pass the strings/values and use the try-catch mechanism to reduce errors and exception during the execution, and print the specific line number in which there is an error.
  • Thread.sleep() command is used to pause the execution for a few seconds so that the user can view the process without hurry.
package com.edureka.uiPackage;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;

public class LoginPage {

WebDriver driver;

public LoginPage(WebDriver driver){
this.driver=driver;
}
@FindBy(how=How.NAME,using="userName")
@CacheLookup
WebElement username;
@FindBy(how=How.NAME,using="password")
@CacheLookup
WebElement password;
@FindBy(how=How.NAME,using="login")
@CacheLookup
WebElement login;

public void loginWordPress(String use, String pass) {
try {
username.sendKeys(use);
Thread.sleep(3000);
password.sendKeys(pass);
Thread.sleep(3000);
login.click();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

Now, let’s see how to find a flight on the web page.

FlightFinder Page

  • First, we’ll create a class FlightFinderPage under which instantiate the webdriver to the driver instance.
  • Find the element on the web page using XPath which is an element locator in Selenium.
  • The element is found on the web page using the location of the web element and the annotations @FindBy and @CacheLookup.
  • Create a function continueWordPress() where we can send the values to the variables declared.
package com.edureka.uiPackage;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;

public class FlightFinderPage {

WebDriver driver;

public FlightFinderPage(WebDriver driver){
this.driver=driver;
}
@FindBy(how=How.XPATH,using="/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[2]/td[2]/b/font/input[1]")
@CacheLookup
WebElement roundTrip;
@FindBy(how=How.XPATH,using="/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[2]/td[2]/b/font/input[2]")
@CacheLookup
WebElement onewayTrip;
@FindBy(how=How.NAME,using="passCount")
@CacheLookup
WebElement passCount;
@FindBy(how=How.NAME,using="fromPort")
@CacheLookup
WebElement fromPort;
@FindBy(how=How.NAME,using="fromMonth")
@CacheLookup
WebElement fromMonth;
@FindBy(how=How.NAME,using="fromDay")
@CacheLookup
WebElement fromDay;
@FindBy(how=How.NAME,using="toPort")
@CacheLookup
WebElement toPort;
@FindBy(how=How.NAME,using="toMonth")
@CacheLookup
WebElement toMonth;
@FindBy(how=How.NAME,using="toDay")
@CacheLookup
WebElement toDay;
@FindBy(how=How.NAME,using="airline")
@CacheLookup
WebElement airline;
@FindBy(how=How.NAME,using="findFlights")
@CacheLookup
WebElement findFlights;

@FindBy(how=How.XPATH,using=".//*[@value='Business']")
@CacheLookup
WebElement serviceClass;

public void continueWordPress(String pCount, String fPort, String fMonth, String fDay, String tPort, String tMonth, String tDate,String serClass, String aline) {
try {
Thread.sleep(2000);
roundTrip.click();
Thread.sleep(2000);
passCount.sendKeys(pCount);
Thread.sleep(2000);
fromPort.sendKeys(fPort);
Thread.sleep(2000);
fromMonth.sendKeys(fMonth);
Thread.sleep(2000);
fromDay.sendKeys(fDay);
Thread.sleep(2000);
toPort.sendKeys(tPort);
Thread.sleep(2000);
toMonth.sendKeys(tMonth);
Thread.sleep(2000);
toDay.sendKeys(tDate);
Thread.sleep(2000);
serviceClass.sendKeys(serClass);
Thread.sleep(2000);
airline.sendKeys(aline);
Thread.sleep(2000);
findFlights.click();
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

And now, let’s understand how to select a flight using Selenium Maven.

SelectFlight Page

  • First, let’s create a class SelectFlightPage where we will instantiate the driver to the instance of the webdriver.
  • The web element is found using the XPath and the location of the element on the web page.
  • The annotations like @CacheLookup and @FindBy are used to specify the element and its location.
  • Create a function departAirlineWordPress() and send the values of the depart airlines. In this, we will check for the name of the flight with the options present, ignoring the cases of the texts. If the names match, it clicks the name of the flight or else throws an exception.
  • Create another function returnAirlineWordPress() to send the values of the return airlines and the same process is repeated.
  • Then continue the process using the try-catch technique so that the errors are caught and pause the execution for a few seconds using a sleep command.
package com.edureka.uiPackage;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;

public class SelectFlightPage {

WebDriver driver;

public SelectFlightPage(WebDriver driver){
this.driver=driver;
}
@FindBy(how=How.XPATH,using="/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table[1]/tbody/tr[3]/td[1]/input")
@CacheLookup
WebElement BlueSkiesAirlines360_D;

@FindBy(how=How.XPATH,using="/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table[1]/tbody/tr[5]/td[1]/input")
@CacheLookup
WebElement BlueSkiesAirlines361_D;

@FindBy(how=How.XPATH,using="/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table[1]/tbody/tr[7]/td[1]/input")
@CacheLookup
WebElement PangaeaAirlines362_D;

@FindBy(how=How.XPATH,using="/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table[1]/tbody/tr[9]/td[1]/input")
@CacheLookup
WebElement UnifiedAirlines363_D;

@FindBy(how=How.XPATH,using="/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table[2]/tbody/tr[3]/td[1]/input")
@CacheLookup
WebElement BlueSkiesAirlines360_T;

@FindBy(how=How.XPATH,using="/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table[2]/tbody/tr[5]/td[1]/input")
@CacheLookup
WebElement BlueSkiesAirlines361_T;

@FindBy(how=How.XPATH,using="/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table[2]/tbody/tr[7]/td[1]/input")
@CacheLookup
WebElement PangaeaAirlines362_T;

@FindBy(how=How.XPATH,using="/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table[2]/tbody/tr[9]/td[1]/input")
@CacheLookup
WebElement UnifiedAirlines363_T;

@FindBy(how=How.XPATH,using="/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/p/input")
@CacheLookup
WebElement con;

public void departAirlineWordPress(String departAirline){
try {
if(departAirline.equalsIgnoreCase("Blue Skies Airlines 360")){
BlueSkiesAirlines360_D.click();
Thread.sleep(2000);
}
if(departAirline.equalsIgnoreCase("Blue Skies Airlines 361")){
BlueSkiesAirlines361_D.click();
Thread.sleep(2000);
}
if(departAirline.equalsIgnoreCase("Pangaea Airlines 362")){
PangaeaAirlines362_D.click();
Thread.sleep(2000);
}
if(departAirline.equalsIgnoreCase("Unified Airlines 363")){
UnifiedAirlines363_D.click();
Thread.sleep(2000);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public void returnAirlineWordPress(String returnAirline){
try {
if(returnAirline.equalsIgnoreCase("Blue Skies Airlines 360")){
BlueSkiesAirlines360_T.click();
Thread.sleep(2000);
}
if(returnAirline.equalsIgnoreCase("Blue Skies Airlines 361")){
BlueSkiesAirlines361_T.click();
Thread.sleep(2000);
}
if(returnAirline.equalsIgnoreCase("Pangaea Airlines 362")){
PangaeaAirlines362_T.click();
Thread.sleep(2000);
}
if(returnAirline.equalsIgnoreCase("Unified Airlines 363")){
UnifiedAirlines363_T.click();
Thread.sleep(2000);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

public void continu() {

con.click();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

After this, we’ll see how one can book a flight.

BookFlight Page

  • This page uses the same annotations as the flight finder and the select flight page that is @FindBy and @CacheLookup.
  • It mainly deals with the user information like name, meal, card number, card details and so on.
  • Create a function purchasePress() where we will provide the values to the variables defined and then,
  • We use the try-catch method here to reduce errors.
package com.edureka.uiPackage;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;

public class BookFlightPage {

WebDriver driver;

public BookFlightPage(WebDriver driver){
this.driver=driver;
}

@FindBy(how=How.NAME,using="passFirst0")
@CacheLookup
WebElement firstName;
@FindBy(how=How.NAME,using="passLast0")
@CacheLookup
WebElement lastName;
@FindBy(how=How.NAME,using="pass.0.meal")
@CacheLookup
WebElement meal;
@FindBy(how=How.NAME,using="creditCard")
@CacheLookup
WebElement cardType;
@FindBy(how=How.NAME,using="creditnumber")
@CacheLookup
WebElement cardNumber;
@FindBy(how=How.NAME,using="cc_exp_dt_mn")
@CacheLookup
WebElement expMonth;
@FindBy(how=How.NAME,using="cc_exp_dt_yr")
@CacheLookup
WebElement expYears;
@FindBy(how=How.NAME,using="cc_frst_name")
@CacheLookup
WebElement cardFirstNames;
@FindBy(how=How.NAME,using="cc_mid_name")
@CacheLookup
WebElement cardMidName;
@FindBy(how=How.NAME,using="cc_last_name")
@CacheLookup
WebElement cardLastName;
@FindBy(how=How.XPATH,using="/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[23]/td/input")
@CacheLookup
WebElement purchase;

public void purchasePress(String fname,String lname,String meal2,String cType,String cNumber,String eMonth,String eYear,String cFirstName,String cMiddleName,String cLastName){
try {
Thread.sleep(2000);
firstName.sendKeys(fname);
Thread.sleep(2000);
lastName.sendKeys(lname);
Thread.sleep(2000);
meal.sendKeys(meal2);
Thread.sleep(2000);
cardType.sendKeys(cType);
Thread.sleep(2000);
cardNumber.sendKeys(cNumber);
Thread.sleep(2000);
expMonth.sendKeys(eMonth);
Thread.sleep(2000);
expYears.sendKeys(eYear);
Thread.sleep(2000);
cardFirstNames.sendKeys(cFirstName);
Thread.sleep(2000);
cardMidName.sendKeys(cMiddleName);
Thread.sleep(2000);
cardLastName.sendKeys(cLastName);
Thread.sleep(2000);
purchase.click();
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

This page gives you an idea of the logout process.

FlightConfirmation Page

  • Find the element by using the element locators like XPath and the annotations like @FindBy and @CacheLookup.
  • Click the logout button on the web page.
package com.edureka.uiPackage;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;

public class FlightConfirmationPage {

WebDriver driver;

public FlightConfirmationPage(WebDriver driver){
this.driver=driver;
}

@FindBy(how=How.XPATH,using="/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr[1]/td[2]/table/tbody/tr[7]/td/table/tbody/tr/td[3]/a/img")
@CacheLookup
WebElement logout;

public void logoutPress(){
logout.click();
}
}

After this, let’s move to the com.edureka.frameworkPackage package. We will learn how can we capture the screenshot of the flight booked.

CaptureScreenShot Page

  • We first create a class CaptureScreenShot() under which we are going to know how to take a screenshot of a particular page.
  • Use the try-catch method to catch the errors being encountered during the execution and throw an exception.
  • Link the object of the CaptureScreenShot to the webdriver object using TakesScreenshot ts = (TakesScreenshot)driver; command.
  • After this, capture & store the screenshot as a file using this command File source = ts.getScreenshotAs(OutputType.FILE);
  • And then, copy the path of the new file and save in the source using FileUtils.copyFile(source, new File(filepath));
  • Execute catch to make sure there are no errors or exceptions while running a case.
  • After this is done, we need to save the screenshots in the .png format and use the date function for displaying the date, month and year in the filename.

package com.edureka.frameworkPackage;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;

public class CaptureScreenShot {

public CaptureScreenShot(){

}

public static void getScreenShot(WebDriver driver, String filepath) {
try {
System.out.println("In getScreenShot method");
TakesScreenshot ts = (TakesScreenshot)driver;
System.out.println("before getScreenshotAs");
File source = ts.getScreenshotAs(OutputType.FILE);
System.out.println("After getScreenshotAs");
FileUtils.copyFile(source, new File(filepath));
} catch (WebDriverException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public static String getDateTimeStamp(){
Date oDate;
String[] sDatePart;
String sDateStamp;
oDate = new Date();
System.out.println(oDate.toString());
sDatePart = oDate.toString().split(" ");
sDateStamp = sDatePart[5] + "_" +
sDatePart[1] + "_" +
sDatePart[2] + "_" +
sDatePart[3] ;
sDateStamp = sDateStamp.replace(":", "_");
System.out.println(sDateStamp);
return sDateStamp;}

}

Once we are done with this, let’s take a look at the next package that deals with the test cases.

HelperClass Page

  • First, create an object of the BrowserFactory, i.e. obj1.
  • The annotations are used to control how the methods will run
  • Before suite, before class, before method, and after suite, after class, after method are a few annotations we are going to use in this project.
  • @Before suite represents an event before the suite starts. So, this method will be executed before the first test declared within the tests.
  • @BeforeClass is used to set up the browser driver properties and initialize the driver.
  • @BeforeMethod checks for the database connection before executing the test method.
  • Link the helper class driver with the Chrome using the command HelperClass.driver = BrowserFactory.getDriver(“chrome”)
  • End the suite, method, and class using @AfterSuite, @AfterMethod and @AfterClass annotations.

package com.edureka.testPackage;

import java.io.IOException;

import org.apache.commons.mail.EmailException;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;

import com.edureka.frameworkPackage.BrowserFactory;
//import com.edureka.frameworkPackage;

public class HelperClass {

public static WebDriver driver;
BrowserFactory obj1;

public HelperClass(){
}

@BeforeSuite
public void beforeSuite(){

}

@BeforeClass
public void beforeClass(){
System.out.println("in @BeforeClass");
}

@BeforeMethod
public void beforeMethodClass(){
System.out.println("in @BeforeMethod");
HelperClass.driver = BrowserFactory.getDriver("chrome");

}

@AfterMethod
public void close()
{
//this.driver.close();
}

@AfterClass
public void afterClass(){

}

@AfterSuite
public void afterSuite() throws IOException, EmailException{

driver.quit();
}
}

And finally, let’s take a look at how these programs are combined together to compute one base class.

TestCaseClass Page

This page holds the details of all the programs in the project starting from the browser driver to providing the values to the functions called in the different programs.

  • All the programs are ultimately integrated to this page of the project where it is called from.
  • The values to the login can be used like LoginPage loginPage = PageFactory.initElements(driver, LoginPage.class);
  • loginPage.loginWordPress(“mercury”, “mercury”); where the loginPage() function is called in this page where we will pass the values like username and password.
  • This process continues for all the pages namely FindFlight, SelectFlight and so on.
  • Try-catch method is used to catch the errors.

 

Find out our Selenium Testing Course in Top Cities

IndiaUnited StatesOther Countries
Selenium Training in IndiaSelenium Training in ChicagoSelenium Certification UK
Selenium Training in KolkataSelenium Training in New YorkSelenium Training in Singapore
Selenium Course in PuneSelenium Training in USASelenium Training Sydney

 

package com.edureka.testPackage;

import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.Test;

import com.edureka.frameworkPackage.BrowserFactory;
import com.edureka.frameworkPackage.CaptureScreenShot;
import com.edureka.uiPackage.BookFlightPage;
import com.edureka.uiPackage.FlightConfirmationPage;
import com.edureka.uiPackage.FlightFinderPage;
import com.edureka.uiPackage.LoginPage;
import com.edureka.uiPackage.SelectFlightPage;

public class TestCaseClass extends HelperClass {

public TestCaseClass(){
}

@Test
public void returnTicket() {
try {
System.out.println("in returnTicket");
driver.get("http://newtours.demoaut.com/");
LoginPage loginPage = PageFactory.initElements(driver, LoginPage.class);
loginPage.loginWordPress("mercury", "mercury");
FlightFinderPage flightFinderpage = PageFactory.initElements(driver, FlightFinderPage.class);
flightFinderpage.continueWordPress("1","Zurich","July","12","Frankfurt","September","15","Business Class","Unified Airlines");
SelectFlightPage selectFlightPage = PageFactory.initElements(driver, SelectFlightPage.class);
selectFlightPage.departAirlineWordPress("Pangaea Airlines 362");
selectFlightPage.returnAirlineWordPress("Unified Airlines 363");
selectFlightPage.continu();
BookFlightPage bookFlightPage = PageFactory.initElements(driver, BookFlightPage.class);
bookFlightPage.purchasePress("Anirudh", "AS", "Vegetarian", "MasterCard", "12345678", "12", "2008", "Anirudh", "A", "S");
FlightConfirmationPage flightConfirmationPage = PageFactory.initElements(driver, FlightConfirmationPage.class);
String bookingDetailsFile = System.getProperty("user.dir")+"\"+"ScreenShotsFlightConfirmationDetails - "+CaptureScreenShot.getDateTimeStamp()+".png";
try {CaptureScreenShot.getScreenShot(BrowserFactory.getDriver(), bookingDetailsFile);
} catch (Exception e) {e.printStackTrace();}

flightConfirmationPage.logoutPress();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

This is everything about the pages we need to create and the functions we need to pass to automate the process of booking a flight.

Now let’s check the output of this project.

Webpage - Selenium Maven - Edureka
Flight finder - Selenium Maven - Edureka

Finds the flights according to the values passed by the user.

Select flight - Selenium Maven - Edureka

Selects the flight accordingly.

Book flight - Selenium Maven - EdurekaBooks a flight by filling up the details like name, card number and so on.

Flight confirmation - Selenium Maven - EdurekaThe details of the flight booked. A confirmation on the flight booked along with the current date.

Screenshot- Selenium Maven with Eclipse- Edureka

Now with this, we come to an end to this “Selenium Maven with Eclipse” blog. I hope you guys enjoyed reading this article and understood how to run a test case in Selenium Course. Got a question for us? Please mention it in the comments section of “Selenium Maven with Eclipse” and we will get back to you.

Upcoming Batches For Selenium Certification Training Course
Course NameDateDetails
Selenium Certification Training Course

Class Starts on 4th May,2024

4th May

SAT&SUN (Weekend Batch)
View Details
Selenium Certification Training Course

Class Starts on 20th May,2024

20th May

MON-FRI (Weekday Batch)
View Details
Selenium Certification Training Course

Class Starts on 25th May,2024

25th May

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

How to Create a Selenium Maven Project in Eclipse IDE?

edureka.co