Selenium is one of the most widely used automation tools for testing a web application. It has outthrown all the traditional ways of testing. 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.
Ever wonder why Selenium is so valuable for testing a web application? What is Selenium? What makes it unique? Let’s unveil the various features that are responsible for this framework’s outstanding demand.
What is Selenium and What are its features?
Selenium is a top-tier technology that helps test web applications and automate their processes. The advancement in testing has also increased the number of people taking the Selenium online course.
- Selenium is an open-source portable framework used to test web applications.
- Test cases can be written in different programming languages, such as Java, Python, Ruby, etc., but Java is the most commonly used 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, which refers to the process of running test cases 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 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 setup by providing a boilerplate for projects or modules.
- It is consistent across different projects.
- It can also work on multiple projects at the same time.
- Able to build any number of projects into its predefined output types, such as a JAR or WAR, without any scripting in most cases.
What is the Eclipse IDE?
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 that provides the nub to the Eclipse IDE is basically composed of plugins.
- It is written mostly in Java and is used primarily to develop Java applications, but it may also be used to develop applications in other programming languages.
- The tool’s license is open-source software that 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, in which our Selenium testing expert explains how to install Selenium on your system.
Download & Install Selenium | Selenium WebDriver Setup | Selenium Installation Guide | Edureka
Why Use Eclipse to Run the Selenium Maven project?
We are considering using the Eclipse platform to work with Selenium Maven because Eclipse IDE is the most popular editor for developing Java applications. It is free, 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, they are 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.
- It helps with refactoring, i.e., 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. The 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.
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 houses all the build’s output, including the compilation results and 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, and any 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 Maven users 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.
Selenium Maven With Eclipse | Maven Selenium Project In Eclipse | Selenium Training | Edureka
This ‘Selenium Maven with Eclipse’ video by Edureka helps you understand how to implement a Selenium Maven project using the Eclipse IDE.
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
Step 1: Create a New Project
Go to File-> Go to New-> Others -> Maven Project to create a new Java project.
Step 2: Add the Dependencies to pom.xml file
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.
Step 4: Write the Code to Run the Test Cases
- BroswerFactory
- Login Page
- FlightFinder Page
- SelectFlight Page
- BookFlight Page
- FlightConfirmation Page
- CaptureScreenShot Page
- HelperClass Page
- TestCaseClass Page
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, in this project, we will use the web element, create an object of it, and find the element by using the element locators in Selenium.
- Create a function loginWordPress(), pass the strings/values, use the try-catch mechanism to reduce errors and exceptions during execution, and print the specific line number in which there is an error.
- The Thread.sleep() command pauses the execution for a few seconds so that the user can view the process without hurrying.
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 Training in Top Cities/Countries
India | Other Cities/Countries |
Bangalore | US |
Hyderabad | UK |
Pune | Canada |
Chennai | Australia |
Mumbai | Singapore |
Kolkata | Edinburgh |
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.
Finds the flights according to the values passed by the user.
Selects the flight accordingly.
Now, we have concluded this “Selenium Maven with Eclipse” blog. I hope you enjoyed reading this article and understood how to run a test case in Selenium. Do you have a question for us? Please mention it in the comments section of “Selenium Maven with Eclipse,” and we will get back to you.