Step 1 – Open the IntelliJ. It will look as shown below. To create a New Project, click on New Project Icon.
Step 2 – Click on File Option, hover on New Option, and click on Project Option as shown below.
Step 3 – Select New Project as Maven. Project SDKshould be current Java version available. Select option for Create from archetype. This will enable the options to select archetype. Select archetype : maven-archetype-quickstart. Click on the Next Button.
Step 4– Below screen will appear. Mention the Name, Group Id, Artifact Id, and Version. Click the Finish button
Name : MavenIntelliJDemo Group Id : com.example Artifact Id : MavenIntelliJDemo Version : 1.0-SNAPSHOT
Step 5 – Verify the information in the below screen. Click onFinish Button.
Step 6 – This dialog box will appear on the screen. This provides you the option to open the project in the current window or will open a new window with this project. I’m selecting the option – New Window.
Step 7 – This screen shows the structure of the Maven project as well as the POM.xml file.
Step 8 – Project Folder Creation – We can see a folder with the name of the project – MavenIntelliJDemo in our Eclipse Workspace.
This is how we can create the Maven project – MavenIntelliJDemo in IntelliJ.
That’s it! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
Page Object model is an object design pattern in Selenium, where web pages are represented as classes, and the various elements on the page are defined as variables in the class and all possible user interactions can then be implemented as methods in the class.
The benefit is that if there is any change in the UI for the page, the tests themselves don’t need to change, only the code within the page object needs to change. Subsequently all changes to support that new UI are located in one place.
Advantages:
1. Readable – There is a clean separation between test code and page specific code such as locators and methods.
2. Maintainability – In this model, separate classes are created for different pages of a web application like login page, the home page, employee detail page, change password page, etc. So, if there is any change in any element of a website then we only need to make changes in one class, and not in all classes.
3. Reusable – If multiple test scripts use the same web elements, then we need not write code to handle the web element in every test script. Placing it in a separate page class makes it reusable by making it accessible by any test script.
4. Easy project Structure– Its project structure is quite easy and understandable.
5. PageFactory – It can use PageFactory in the page object model in order to initialize the web element and store elements in the cache.
In case there are lots of web elements on a page, then the object repository class for a page can be separated from the class that includes methods for the corresponding page.
Example: If the New Customer page has many input fields. In that case, there can be 2 different classes. One class called NewCustomerObjects.java that forms the object repository for the UI elements on the register accounts page.
A separate class file NewCustomerMethods.java extending or inheriting NewCustomerObjects that includes all the methods performing different actions on the page could be created.
Consider the below script to login to an application and navigate to home page.
This is a small script. Therefore, script maintenance and readability looks very easy.
Imagine there are 50 different tests present in this script. In that case, the readability of the script decreases as well as maintenance become very difficult.
Scenario
Launch the Firefox browser.
The demo website opens in the browser.
Verify the Login Page
Enter username and Password and login to the demo site.
PageFactory is a way of implementing the “Page Object Model”. Here, we follow the principle of separation of Page Object Repository and Test Methods. It is an inbuilt concept of Page Object Model which is very optimized.
1. The annotation @FindBy is used in Pagefactory to identify an element while POM without Pagefactory uses the driver.findElement() method to locate an element.
2. The second statement for Pagefactory after @FindBy is assigning an <element name> of type WebElement class that works exactly similar to the assignment of an element name of type WebElement class as a return type of the method driver.findElement() that is used in usual POM (userName in this example).
3. Below is a code snippet of non PageFactory Mode to set Firefox driver path. A WebDriver instance is created with the name driver and the FirefoxDriver is assigned to the ‘driver’. The same driver object is then used to launch the demo website, locate the webelements and to perform various operations
Basically, here the driver instance is created initially and every web element is freshly initialized each time when there is a call to that web element using driver.findElement() or driver.findElements().
ChromeOptions options = new ChromeOptions();
driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://opensource-demo.orangehrmlive.com/");
But with POM with PageFactory approach, all the elements are initialized with initElements() without explicitly initializing each web element.
The initElementsis a static method of PageFactory class which is used to initialize all the web elements located by @FindBy annotation. Thus, instantiating the Page classes easily. It is used to initialize the WebElements declared, using driver instance from the main class. In other words, WebElements are created using the driver instance. Only after the WebElements are initialized, they can be used in the methods to perform actions.
public Login(WebDriver driver) {
this.driver = driver;
// This initElements method will create all WebElements
PageFactory.initElements(driver, this);
}
3.2 Create methods for actions performed on WebElements.
Below actions are performed on WebElements in Login Page:
Get Text on Login Page
Type action on the Username field.
Type action in the Password field.
Click action on the Login Button
Note: A constructor has to be created in each of the class in the Page Layer, in order to get the driver instance from the Main class in Test Layer and also to initialize WebElements(Page Objects) declared in the page class using PageFactory.InitElement().
BaseClass
package com.example.pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
public class BasePage {
public WebDriver driver;
public BasePage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver,this);
}
}
Login Page
package com.example.pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class LoginPage extends BasePage{
public LoginPage(WebDriver driver) {
super(driver);
}
@FindBy(name = "username")
public WebElement userName;
@FindBy(name = "password")
public WebElement password;
@FindBy(xpath = "//*[@class='oxd-form']/div[3]/button")
public WebElement login;
@FindBy(xpath = "//*[@id='app']/div[1]/div/div[1]/div/div[2]/div[2]/div/div[1]/div[1]/p")
public WebElement errorMessage;
public void login(String strUserName, String strPassword) {
userName.sendKeys(strUserName);
password.sendKeys(strPassword);
login.click();
}
public String getErrorMessage() {
return errorMessage.getText();
}
}
HomePage. java
package com.example.pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class HomePage extends BasePage {
public HomePage(WebDriver driver) {
super(driver);
}
@FindBy(xpath = "//*[@id='app']/div[1]/div[1]/header/div[1]/div[1]/span/h6")
public WebElement homePageUserName;
public String getHomePageText() {
return homePageUserName.getText();
}
}
Step 4 – Create test class for the tests of these pages
BaseTests
package com.example.tests;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import java.time.Duration;
public class BaseTests {
public static WebDriver driver;
public final static int TIMEOUT = 10;
@BeforeMethod
public void setup() {
ChromeOptions options = new ChromeOptions();
options.addArguments("--remote-allow-origins=*");
options.addArguments("--no-sandbox");
options.addArguments("--disable-dev-shm-usage");
options.addArguments("--headless");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.get("https://opensource-demo.orangehrmlive.com/");
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(TIMEOUT));
}
@AfterMethod
public void tearDown() {
driver.quit();
}
}
LoginPageTests.java
package com.example.tests;
import com.example.pages.HomePage;
import com.example.pages.LoginPage;
import org.testng.Assert;
import org.testng.annotations.Test;
public class LoginPageTests extends BaseTests{
String actualResponse;
@Test
public void invalidCredentials() {
LoginPage objLoginPage = new LoginPage(driver);
objLoginPage.login("admin", "admin");
actualResponse = objLoginPage.getErrorMessage();
Assert.assertEquals(actualResponse,"Invalid credentials");
}
@Test
public void validCredentials() {
LoginPage objLoginPage = new LoginPage(driver);
objLoginPage.login("Admin", "admin123");
HomePage objHomePage = new HomePage(driver);
actualResponse = objHomePage.getHomePageText();
Assert.assertEquals(actualResponse,"Dashboard");
}
}
Step 5 – Execute the tests
To run the test, right click and select as Run As and then select TestNG Test (Eclipse).
Right-click on the LoginPageTests and select Run ‘LoginPageTests’ (IntelliJ)
Step 6 – Create TestNG.xml
You can add TestNG.xml and run the tests from there also.
<?xml version = "1.0"encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name = "PageObjectModel">
<test name = "PageObjectModel Tests">
<classes>
<class name ="com.example.tests.LoginPageTests"/>
</classes>
</test>
</suite>
Step 7 – Run the tests from TestNG.xml
Right click on TestNG.xml and select Run As TestNG Suite.
The execution status looks like as shown below.
Step 8 -TestNG Report Generation
Once the execution is finished, refresh the project. It will create a test-output folder containing various reports generated by TestNG. Below is the screenshot of the report folder.
Index.html
emailable-report.html
Step 9 – Execute the tests through command line
We can run the tests through command line. Use the below command:
New version of Eclipse like Photon or Eclipse IDE 2019-06 has M2_REPO classpath variable after integrating maven plugins (m2eclipse) with Eclipse IDE, M2_REPO classpath variable gets added –> pointing to default locations (for example c:\Users\\.m2\repository) and this variable is non-modifiable. However, if we are using older version of Eclipse, then we need to add M2_REPO manually to Eclipse.
Steps to add M2_REPO
Open Eclipse IDE, select Window ->Preferences ->Java ->Classpath Variables
2. Click on New Button. Add below mentioned information:-
Name – M2_REPO
Path – Path where M2 file places in your system
Eg – C:\Users\SingVi04\.m2\repository
Note:- I have already added M2_REPO, so we can see an error message – Variable name already exists.
3. Verify that M2_REPO add – You can check new Classpath variable M2_REPO is added under BuildPath ->Classpath Variables
4. The m2e plugin will analyze the pom.xml and will configure the project and generate the Eclipse files automatically.
5. Below is the code of App.java. Run this code
package com.Selenium;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
6. Below is the code of AppTest.java. Run this code
package com.Selenium;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
/**
* Unit test for simple App.
*/
public class AppTest
{
/**
* Rigorous Test 🙂
*/
@Test
public void shouldAnswerWithTrue()
{
assertTrue( true );
}
}
Note:- Apache Maven Eclipse Plugins like eclipse:eclipse, eclipse:clean, etc are retired. To know more about it, please refer the link
7. Structure of POM.xml
<?xml version="1.0"encoding="UTF-8"?>
<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.Selenium</groupId>
<artifactId>MavenProjectFromCMD</artifactId>
<version>1.0-SNAPSHOT</version>
<name>MavenProjectFromCMD</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<pluginManagement><!-- lock down plugins versions to avoid using Mavendefaults (may be moved to parent pom) -->
<plugins>
<!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
<!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
In the previous tutorial, we have discussed about How to install Maven on Windows. In this tutorial, we will see how to use Maven to manage a Java project – Create and update the dependencies.
1) Change current folder to the folder where we want to create the Java project
In my case I have my Eclipse Workspace mentioned at the below mentioned path
cd C:\Users\vibha\eclipse-workspace\Selenium
2) Create a Project from Maven Template
This tells Maven to generate a Java project from a Maven template.
mvn archetype:generate
3) We need to mention the number as displayed on your screen in Command Prompt to proceed further. Like here, Choose a folder or apply has 1394, so I have also mentioned 1394 in command prompt.
4) We need to provide again input in command prompt. This time program wants to know which version we want to use. I prefer to use the latest version. Here, it is 8, so I have selected version 8.
5) We need to provide 2 input here
A) Value of groupId – This serves as the group identifier of your Maven project, it should be in a form similar to Java packages, such as com.Selenium B) Value of artifactId – This serves as the group-local identifier of my Maven project like MavenProjectFromCMD C) Value of Version – The initial version of our project. The default is 1.0-SNAPSHOT D) Value of package – The name of our root package. The default is groupId we have created earlier. We will notice the INFO message about the properties. If the displayed settings are correct, then just enter Y in :: prompt.
Successful Build – Below screenshot shows that the Maven Project built successfully.
6) Project Folder Creation – We can see a folder with the name of project – MavenProjectFromCMD in our Eclipse Workspace. In my case, it is
Apache Maven is a software project management and comprehension tool. It uses the concept of a project object model (POM), Maven can manage a project’s build and reporting, and documentation from a central piece of information. MAVEN helps us in creating the project structure and managing and downloading the dependencies. We need to define the required dependencies in pom.xml.
Prerequisite:
Maven 3.3+ require JDK 1.7 or above to execute
Approximately 10MB is required for the Maven installation
Installation Steps
Step 1– To install Apache Maven on the window, we need to download Maven’s zip folder from the Official Maven Site. Download apache-maven-3.8.6-bin.zip.
Step 2 – Unzip the downloaded folder and then it will have below-mentioned files. We do not need to install anything, just unzip the folder.
Step 3 – We need to configure MAVEN_HOME environment variable. Type – “View Adva” in the search option, and we will see the option – View Advanced system setting.
Step 4 – In the System Properties dialog, select the Advanced tab and click on the Environment Variables button.
Step 5 – In the “Environment variables” dialog, underUsers variables, Click on the New button and add a MAVEN_HOME variable.
Step 6 – A dialog box will appear, mentioning Variable Name – MAVEN_HOME and Variable value – mention the path where the Apache folder is placed.
Step 7 – Add %MAVEN_HOME%\bin(full path till bin where Maven is placed on your machine) to Path present under System variables. Click the New Button present in System Variable and add MAVEN_HOME\bin.
Step 8 – Once the Path is updated with %MAVEN_HOME%\bin. This is what it will look like.
Step 9 – We have to make sure that JDK is installed and the JAVA_HOME environment variable is configured. If the JAVA_HOME variable is not configured, then add JAVA_HOME just like MAVEN_HOME in User Variable within Environment Variables.
How to verify if Maven is installed properly on your machine
Open the command prompt and type mvn -version, then the screen should look something like as shown below screen
This confirms that Maven is installed successfully and configured on your machine.
As the software development process changes from waterfall to Agile methodology, it becomes essential to use automation for testing. The reason is now there are frequent productions, so to perform regression testing, it is advisable to use automation. Automation testing means using an automation tool to execute the test scripts. This reduces human intervention, which results in avoiding any human error as well as reduces the test execution time. Automation testing is preferable for those test scripts which are executed repeatedly and execution is time-consuming. Saying this, one should keep in mind that we can’t automate everything. The ideal scenario is to automate that part whose ROI (Return on Investment) is higher in terms of automation.
What is Selenium??
Firstly, Selenium is not a single automation tool like QTP, but it is basically a suite of software or a set of JAR files to automate web browsers across various browsers. Selenium is used by many companies, but a few to mention are Netflix, Google, HubSpot, Fitbit, and more.
Selenium Packages
Selenium IDE (Integrated Development Environment) – It is an add-on feature on Mozilla Firefox and Chrome. It is a playback and recording tool. You don’t need to know any language for using this tool.
Selenium RC (Selenium 1.0) – RC means Remote Control. Selenium RC was the main Selenium project for a long time before the WebDriver/Selenium merge brought up Selenium 2, the newest and more powerful tool. Selenium RC is a tool that allows you to write automated web application UI tests in any programming language against any HTTP website using any mainstream enabled JavaScript enabled browser.
Selenium Grid – Grid supports parallel execution, which means multiple test scripts can be executed at the same time on multiple browsers. Selenium Grid supports distributed test execution. So, it will speed up the test execution.
Selenium Grid follows Hub-node architecture. The Hub knows the configuration of each node connected to it. When the Hub receives the information that a test needs to be run along with browser and OS information, then it checks for the available node with the same combination and sends the Selenium command to that node.
Selenium WebDriver – This is the latest version of Selenium. In WebDriver, web elements are identified on a web browser and then actions are performed on these web elements. Selenium WebDriver supports the testing of dynamic pages where web elements change without reloading the page. WebDriver overcomes the problem of single host origin policy which is present in RC. There is a website that is using Selenium to run an asynchronous job in their flask webapp. For more detail, you can refer the website – ExamDeewana.
What is a Single Host Origin Policy ??
This is an important aspect of the web application security model. As per this policy, a web browser allows scripts present on the first web page to access the data on the second web page, provided both the web pages have the same origin, which means the URI scheme, hostname, and port number are the same.
Why Selenium??
We know that there are a lot of automation tools in the market like QTP, RFT (Rational Functional Tester), and so on, then why Selenium is so famous.
1) Open Source – Selenium is an open-source tool, which means no associated cost of licensing. So, it is very cost-effective in the terms of automating the testing.
2) Supports multiple languages, browsers, and Operating systems – Selenium supports multiple languages like Python, Pearl, Ruby, .Net, Java, C#, and PHP. You do need not to know multiple languages to start using Selenium. You should be proficient in any one of the above-mentioned languages and good to go. One of the most important features is that you do need not create the test script in the same language in which the web application is created. Suppose a web application is developed using JavaScript, but we can use any of the above mentioned languages to create Selenium test cases. Selenium supports a range of browsers like Google Chrome, IE, Mozilla, Opera, Microsoft Edge, Safari, and Html Driver. It also supports different operating systems such as Windows, MAC, Linux, Android, iOS.
3) Supports Parallel and Cross Browser Testing – Selenium supports parallel test execution. That means we can open multiple browsers at the same time and execute the test cases. This decrease the execution time significantly. Selenium supports Cross browser test execution. This refers to the fact that we can open different browsers like IE and Chrome and execute the same test cases or different test cases at the same time. This increases the coverage of test execution
4) Supports Integration with DevOps, and Continuous Integration flow – Selenium can be easily integrated with various third-party tools like Jenkins, Maven, TestNG, JUnit, and Git.
4.1Jenkins – Jenkins is a continuous integration tool and can be integrated with Selenium. Jenkins is used for automatic test execution. That means whenever there is any change in software, Jenkins allows you to run the tests every time and deploy the changes to a new environment when the tests pass. Jenkins is also used for scheduling the tests to run at a specific time. 4.2 Maven – Maven is a build management tool, based on the concept of Page Object Model (POM). It is used to define the structure of the project, dependencies, and build and test management. POM.xml file contains information about the version of web driver. It automatically downloads the necessary files from the repository to the local repository. 4.3TestNG – TestNG is an open-source automation testing framework. It helps to group and prioritize the test scripts and support data parameterization and reporting features. 4.4Git– Git is an open-source version control system. It allows committing the work locally and then syncing the local copy of the repository with a copy of the server.
5) Framework Compatibility – Selenium supports various test automation frameworks like Data Driven, Keyword, or Hybrid. Users can select any type of framework depending on the project requirement. Selenium has lots of methods to locate the elements in a webpage such as DOM, CSS, XPath, and so on. It can also be used to test web applications that use JavaScript and AJAX technologies.
6) Supports mobile Testing – Selenium doesn’t perform mobile testing. But it supports mobile testing with the help of additional software like Selendroid and Appium. This software is based on Selenium, so anyone who is well-versed in selenium can apply the same principles for mobile app testing.
7) Supports Database Testing – Selenium WebDriver in itself can’t perform Database Testing, but this can be done by using WebDriver with JDBC (“Java Database Connectivity”) API. The API lets the user connect and interact with the data source and fetch the data with the help of automated queries.
8) System Compatibility – Internet Explorer(IE) and Google Chrome support both 32-bit and 64-bit versions, where you can download and use them based on your system requirement.
9) Selenium 4.0 – In Selenium 4.0, all the vendors like Google, Apple, Microsoft, and Firefox have their own drivers to work on Selenium. Selenium 4.0 supports Selenium Grid and Selenium WebDriver and stops using Selenium RC directly. Selenium Core is completely removed from the latest version of Selenium 3.0.
Like any other tool, Selenium also has some limitations, such as:-
1) Programming knowledge is needed – Selenium does not support codeless test automation. Testers need to know any one of the programming languages which are supported by selenium.
2) No Image Comparison – Selenium doesn’t support image comparison. To perform image comparison, selenium needs to be integrated with a third-party tool called – Sikuli
3) No Official Customer Service Support – It’s an open-source tool, so there is no official customer support team to address your issues. You can get support from tutorials, chat rooms, and online support, but not from product creators.
4) No Reporting facility – The lack of automation of report generation is one of the biggest disadvantages. But, there are third-party tools that overcome this problem like TestNG, JUnit, Extent Library, and Allure.
Architecture
WebDriver talks to a browser through a driver. Communication is two-way: WebDriver passes commands to the browser through the driver and receives information back via the same route. The driver is specific to the browser, such as ChromeDriver for Google’s Chrome/Chromium, GeckoDriver for Mozilla’s Firefox, etc. The driver runs on the same system as the browser.