Setup Basic REST Assured Gradle Project In Eclipse IDE

HOME

In the previous tutorial, I have provided the Introduction of Rest Assured. In this tutorial, I will explain how to setup basic Rest Assured Gradle project in Eclipse IDE. Before going through this tutorial, it is recommended to go through previous tutorial to know about Rest Assured.

What is Gradle?

Gradle is an open-source build automation tool that is designed to be flexible enough to build almost any type of software. A build automation tool is used to automate the creation of applications. The building process includes compiling, linking, and packaging the code. The process becomes more consistent with the help of building automation tools.

Steps to setup Rest Assured Gradle Project in Eclipse

  1. Download and Install Java on the system
  2. Download and setup Eclipse IDE on the system
  3. Setup Gradle on System
  4. Create a new Gradle Project
  5. Add Rest-Assured dependencies to the project

Step 1- Download and Install Java

Rest-Assured needs Java to be installed on the system to run the tests. Check if Java is installed on your machine or not by using the below command on Command Prompt.

java -version

If Java is not installed, then click here to know How to install Java.

Step 2 – Download and setup Eclipse IDE on the system

The Eclipse IDE (integrated development environment) provides strong support for Java developers. If Eclipse IDE is already not present on your system, then click here to know How to install Eclipse.

Step 3 – Setup Gradle

To build a test framework, we need to add several dependencies to the project. This can be achieved by any build Tool. I have used Gradle Build Tool. Click here to know How to install Gradle.

Step 4 – Create a new Gradle Project

To know, in detail, how to create a Gradle project in Eclipse, refer to this link.

File ->New Project ->Gradle Project ->Next.

Provide projectname and location where you want to save the project on your system. Click the Finish Button.

Verify the Gradle Version and Gradle project structure name. Click the Finish Button.

Below is the structure of the new Gradle project.

Below is the structure and content of the build.gradle of the new project.

Step 5 – Add Rest-Assured dependencies to the project

Add Rest-Assured, JSON Schema Validator, and JUnit dependencies to the project.

    // Use rest assured
    testImplementation 'io.rest-assured:rest-assured:4.3.3'
    testImplementation 'io.rest-assured:json-schema-validator:4.3.3'

Step 6 – Below are the Rest Assured, json schema validator, junit jar files present under Maven Dependencies.

Make sure you right-click on project -> Select Gradle ->Refresh Gradle Project. It is needed to see the new jar files in the project.

That’s it! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers

Advertisement

Setup Basic REST Assured Maven Project In Eclipse IDE

HOME

In the previous tutorial, I have provided the Introduction of Rest Assured. In this tutorial, I will explain how to setup basic Rest Assured Maven project in Eclipse IDE. Before starting, let us recap about Rest Assured.

What is Rest Assured?

REST Assured is a Java DSL for simplifying testing of REST based services built on top of HTTP Builder. It supports POST, GET, PUT, DELETE, OPTIONS, PATCH and HEAD requests and can be used to validate and verify the response of these requests.

Rest-Assured library also provides the ability to validate the HTTP Responses received from the server. This makes Rest-Assured a very flexible library that can be used for testing.REST Assured can be used to test XML as well as JSON based web services. REST Assured can be integrated with JUnit and TestNG frameworks for writing test cases for our application.

What is Maven?

Apache Maven is a software project management and comprehension tool. Based on the concept of a project object model (POM), Maven can manage a project’s build, reporting and documentation from a central piece of information.

Steps to setup Rest Assured Maven Project in Eclipse

  1. Download and Install Java on the system
  2. Download and setup Eclipse IDE on the system
  3. Setup Maven on System
  4. Create a new Maven Project
  5. Add Rest-Assured dependencies to the project

Step 1- Download and Install Java

Rest-Assured needs Java to be installed on the system to run the tests. Click here to know How to install Java.

Step 2 – Download and setup Eclipse IDE on system

The Eclipse IDE (integrated development environment) provides strong support for Java developers. Click here to know How to install Eclipse.

Step 3 – Setup Maven

To build a test framework, we need to add several dependencies to the project. Click here to know How to install Maven.

Step 4 – Create a new Maven Project

File -> New Project-> Maven-> Maven project ->Next

Step 4.1 – Select “Create a simple project”. Click on the Next Button.

Step 4.2 – Provide Group Id and Artifact Id and click on the finish button.

Group Id – com.example
Artifact Id – restassured_demo

Step 4.3 – Below is the structure of Maven project in Eclipse.

Step 4.4 – This is the structure of POM.xml created for the project.

Step 5 – Add Rest-Assured, Json Schema Validator and JUnit dependencies to the project .

<dependencies>
  
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    <scope>test</scope>
</dependency>
  
<!-- https://mvnrepository.com/artifact/io.rest-assured/rest-assured -->
<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>4.3.3</version>
    <scope>test</scope>
</dependency>
 
<!-- https://mvnrepository.com/artifact/com.github.fge/json-schema-validator -->
<dependency>
    <groupId>com.github.fge</groupId>
    <artifactId>json-schema-validator</artifactId>
    <version>2.2.6</version>
</dependency>
   
</dependencies>

Step 6 – Below are the Rest Assured , json schema validator, junit jar files present under Maven Dependencies.

Points to Remember

  1. Don’t add dependency of JSONPath and XMLPath explicitly. RestAssured includes both by default. You can see it in the Maven Dependencies folder under your project.

2. Don’t add dependency of Hamcrest explicitly. RestAssured includes it by default. You can see in the Maven Dependencies folder under the project. 

How to create Java Gradle project in Eclipse

HOME

In the previous tutorial, I have explained how to create a Java Gradle project in IntelliJ. In this tutorial, I will explain about creating a Java Gradle project Eclipse. I have used Gradle 6.6 to create the project.

Steps to follow:-

Step 1 – To create a project – Click on New and then select  – Project.

Step 2 – Select Gradle Project and click on the Next button.

Step 3- A welcome screen will appear. You can uncheck the box – Show the welcome page the next time the wizard appears. This is optional. Click the NEXT button.

Step 4 – Below the screen will appear. Mention the Project NameGradleEclipseDemo. Mention the location where we want to save the project in the system. Click the NEXT button.

Step 5 – Options screen appear. Make sure you use Gradle version 6.6 to create Gradle project in Eclipse for Version: 2021-03 (4.19.0).

Note:- If you will try to use version higher than 6.6, then Gradle project structure will have a Gradle project with the nested project with a lib subproject in it.

Step 6 – Verify the Gradle Version and Gradle project structure name.

Step 7 – Below is the structure of Gradle project. The init task generates the new project with the following structure:-

  1. Generated folder for wrapper files -wrapper
  2. Gradle wrapper start scripts – gradlew, gradlew.bat
  3. Settings file to define build name and subprojects – settings.gradle
  4. Build script of lib project – build.gradle
  5. Default Java source folder – src/main/java
  6. Default Java test source folder – src/test/java

Step 8 – Below is the structure and content of the build.gradle.

/*
 * This file was generated by the Gradle 'init' task.
 *
 * This generated file contains a sample Java Library project to get you started.
 * For more details take a look at the Java Libraries chapter in the Gradle
 * User Manual available at https://docs.gradle.org/6.6/userguide/java_library_plugin.html
 */

plugins {
    // Apply the java-library plugin to add support for Java Library
    id 'java-library'
}

repositories {
    // Use jcenter for resolving dependencies.
    // You can declare any Maven/Ivy/file repository here.
    jcenter()
}

dependencies {
    // This dependency is exported to consumers, that is to say found on their compile classpath.
    api 'org.apache.commons:commons-math3:3.6.1'

    // This dependency is used internally, and not exposed to consumers on their own compile classpath.
    implementation 'com.google.guava:guava:29.0-jre'

    // Use JUnit test framework
    testImplementation 'junit:junit:4.13'
}
  1. plugins – Apply the java-library plugin for API and implementation separation.
  2. jcenter – Use JCentral for resolving dependencies. JCenter is a central repository on JFrog Bintray platform for finding and sharing popular JVM language packages in Maven format
  3. api – This dependency is exported to consumers, that is to say found on their compile classpath.
  4. implementation – This dependency is used internally, and not exposed to consumers on their own compile classpath.
  5. testImplementation – Use JUnit test framework.

Step 9 – To check if the project is created sucessfully. In gradle tasks tab -> navigate to the project -> expand build folder -> right click on build -> Select Run Gradle tasks.

This will be the output of the Gradle Run.

That’s it. We have successfully created a Gradle Java project in Eclipse.

Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!

How to import Java Gradle project in Eclipse

HOME

In the previous tutorial, I have explained How to create a Java Gradle project using Command Line. This tutorial will explain How to import Java Gradle project in Eclipse.

Steps to follow:-

Step 1 – Open Eclipse IDE. In Eclipse IDE, select File ->Import ->Maven ->Existing Gradle Project. Click NEXT Button.

Step 2 – A welcome screen will appear. You can uncheck the box – Show the welcome page the next time the wizard appears. This is optional. Click the NEXT button.

Step 3 – Browse the location from where you want to import the Gradle project. Click the NEXT button.

Step 4 – This screen allows us to Configure Customized Workspace Settings. This shows that Gradle Version 7.0 is used for this project. Click Finish Button.

Step 5 – This screen allows us to review import configuration. If you feel something is incorrect, click BACK Button.

Step 6 – We can see that the Gradle project Name is Gradle and other details like Version. Click FINISH Button. This will import the project structure in Workspace.

Step 7 – Below is the imported project Structure in Eclipse.

Step 8 – To check if the project is imported successfully. Run GradleDemo.java class by right click on java class and Run As Java Application.

That’s it! We have imported a Gradle Project in Eclipse.

Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!

Gradle Tutorials

HOME

Gradle is an open-source build automation tool that is designed to be flexible enough to build almost any type of software.
Gradle runs on the JVM and you must have a Java Development Kit (JDK) installed to use it.
Several major IDEs allow you to import Gradle builds and interact with them: Android Studio, IntelliJ IDEA, Eclipse, and NetBeans.

Installation of Gradle

Chapter 1 How to install Gradle on Windows

Creation of Gradle project

Chapter 1 How to create Java Gradle project in Eclipse
Chapter 2 How to create a Java Gradle project using Command Line
Chapter 3 How to create Gradle project in IntelliJ
Chapter 4 How to create Gradle Java project in IntelliJ using Command Line

Importing of Gradle Project

Chapter 1 How to import Java Gradle project in Eclipse
Chapter 2 How to import Java Gradle project in IntelliJ

Gradle Project in Cucumber

Chapter 1 How To Create Gradle Project with Cucumber to test Rest API
Chapter 2 Run Gradle Cucumber Tests from Command Line
Chapter 3 Gradle Project with Cucumber, Selenium and TestNG
Chapter 4 Gradle Project with Cucumber, Selenium and JUnit4

Gradle Project in Serenity

Chapter 1 Serenity BDD with Gradle and Cucumber for Web Application
Chapter 2 Serenity BDD with Cucumber and Rest Assured in Gradle
Chapter 3 Serenity Emailable Report in Gradle

Gradle Project with Selenium

Chapter 1 How to create Gradle project with Selenium and TestNG
Chapter 2 How to create Gradle project with Selenium and JUnit4
Chapter 3 Gradle – Integration of Selenium and JUnit5

Gradle Project in Rest API

Chapter 1 Setup Basic REST Assured Gradle Project In Eclipse IDE

Allure Reports for Gradle Project

Chapter 1 Gradle – Allure Report for Selenium and TestNG
Chapter 2 Gradle – Allure Report for Selenium and JUnit4
Chapter 3 Gradle – Allure Report for Cucumber, Selenium and TestNG

Extent Reports for Gradle Project

Chapter 1 Gradle – Extent Report Version 5 for Cucumber, Selenium, and TestNG

Gradle with Jenkins

Chapter 1 Integrate Gradle project with Jenkins
Chapter 2 How to create Jenkins pipeline for Gradle project

How to create a Java Gradle project using Command Line

HOME

In the previous tutorial, I have explained about How to create Gradle project in IntelliJ without Command Line. In this tutorial, I will explain how to create a Gradle Java project using Command Line.

Step 1 – Open Command Prompt. Change current folder to the folder where we want to create the Java project. 

 cd C:\Users\vibha\eclipse-workspace\Projects\Vibha_Personal\Gradle_Project

Step 2 – Create a Project from Gradle Template. Type the below command and press ENTER.

gradle init

Step 3 – Select the type of project to generate. I’m selecting the application option as if I select basic, it won’t create a src directory. Type 2 and press ENTER.

Step 4 – Select implementation language. This is a Java project, so TYPE 3 and press ENTER.

Step 5 – Select Split functionality across multiple subprojects. I have selected 1 as I want only 1 application. Type 1 and press ENTER.

Step 6 – Select build script DSL (Domain Specific Language) – As in Maven POM.xml (XML) is created to build a script file, here we can use Groovy or Kotlin to build the script file. Type 1 (Groovy) and press ENTER.

Step 7 – Select Test Framework – There are 4 different test frameworks. Depending on your requirement, select an option. I have selected 1 (JUnit 4) and press ENTER.

Step 8 – It needs the Project name and Source Package name. If I won’t provide the project name, it will take by default my current folder name which is Gradle_Project. Similarly, if I won’t provide the Source Package name, then it will provide the current project name as Source Package Name.

Project name – GradleDemoFromCMD
Source Package – com.example

Press ENTER. init script will run and create a Gradle project. You can see as the build is successfull.

Step 9 – Below is the project structure. As you can see, the name of the project is GradleDemoFromCMD, but that is not the name of the project folder here. But, when I’ll import this folder into Eclipse, the project name will be GradleDemoFromCMD.

Step 10 – Open app folder. There should be src folder and build.gradle. Open build.gradle.

/*
 * This file was generated by the Gradle 'init' task.
 *
 * This generated file contains a sample Java application project to get you started.
 * For more details take a look at the 'Building Java & JVM projects' chapter in the Gradle
 * User Manual available at https://docs.gradle.org/7.0/userguide/building_java_projects.html
 */

plugins {
    // Apply the application plugin to add support for building a CLI application in Java.
    id 'application'
}

repositories {
    // Use Maven Central for resolving dependencies.
    mavenCentral()
}

dependencies {
    // Use JUnit test framework.
    testImplementation 'junit:junit:4.13.1'

    // This dependency is used by the application.
    implementation 'com.google.guava:guava:30.0-jre'
}

application {
    // Define the main class for the application.
    mainClass = 'com.example.App'
}

This build.gradle contains all the information which I have provided while creating the project.

That’s it! We have created a Gradle Project using Command Line.

Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!

Page Object Model with Selenium, Cucumber and JUnit

HOME

In this tutorial, I’ll create a BDD Framework for the testing of web applications using the Page Object Model.

This framework consists of

  1. Cucumber Java – 7.6.0
  2. Cucumber JUnit4 – 7.6.0
  3. Java 11
  4. Maven – 3.8.6
  5. Selenium – 4.3.0
  6. JUnit – 4.13.2

What Is Page Object Model (POM)?

The Page Object model is an object design pattern in Selenium, where web pages are represented as classes, 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.

What is Cucumber?

Cucumber is one such open-source tool, which supports Behavior Driven Development(BDD). In simple words, Cucumber can be defined as a testing framework, driven by plain English. It serves as documentation, automated tests, and development aid – all in one.

Steps to setup Cucumber Test Automation Framework using Page Object Model

  1. Download and Install Java on the system
  2. Download and setup Eclipse IDE on the system
  3. Setup Maven on System
  4. Install Cucumber Eclipse Plugin (Only for Eclipse IDE)
  5. Create a new Maven Project
  6. Create a source folder – src/test/resources to create test scenarios in the Feature file
  7. Add Selenium, Cucumber and JUnit4 dependencies to the project
  8. Add Maven Compiler Plugin and Surefire Plugin
  9. Create a feature file under src/test/resources
  10. Create the classes for locators, actions and utilities in src/main/java
  11. Create a Java Class called Definition where we will create the Test Code related to Given, When, Then of Feature file in src/test/java.
  12. Create a Hook class to contain the initialization and closing of browser in src/test/java
  13. Create a Cucumber Runner class in the src/test/java directory
  14. Run the tests from JUnit
  15. Run the tests from Command Line
  16. Cucumber Report Generation

Project Structure

Step 1- Download and Install Java

Cucumber and Selenium need Java to be installed on the system to run the tests. Click here to know How to install Java.

Step 2 – Download and setup Eclipse IDE on the system

The Eclipse IDE (integrated development environment) provides strong support for Java developers. Click here to know How to install Eclipse.

Step 3 – Setup Maven

To build a test framework, we need to add a number of dependencies to the project. Click here to know How to install Maven.

Step 4 – Install Cucumber Eclipse Plugin

The cucumber plugin is an Eclipse plugin that allows eclipse to understand the Gherkin syntax. When we are working with cucumber we will write the feature files that contain Feature, Scenario, Given, When, Then, And, But, Tags, Scenario Outline, and Examples. By default, eclipse doesn’t understand these keywords so it doesn’t show any syntax highlighter. Cucumber Eclipse Plugin highlights the keywords present in Feature File. Refer to this tutorial to get more detail – How to setup Cucumber with Eclipse.

Step 5 – Create a new Maven Project

To create a new Maven project, go to the File -> New Project-> Maven-> Maven project-> Next -> Enter Group ID & Artifact ID -> Finish.

Click here to know How to create a Maven project

Step 6 – Create source folder src/test/resources to create test scenarios in the Feature file

A new Maven Project is created with 2 folders – src/main/java and src/test/java. To create test scenarios, we need a new source folder called – src/test/resources. To create this folder, right-click on your maven project ->select New ->Java and then Source Folder.

Mention the source folder name as src/test/resources and click the Next button. This will create a source folder under your new Maven project as shown in the below image.

Step 7 – Add Selenium, JUnit4, and Cucumber dependencies to the project

Add below mentioned Selenium, JUnit4, and Cucumber dependencies to the project. I have added WebDriverManager dependency to the POM.xml to download the driver binaries automatically. To know more about this, please refer to this tutorial – How to manage driver executables using WebDriverManager.

    <properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<cucumber.version>7.6.0</cucumber.version>
		<selenium.version>4.3.0</selenium.version>
		<webdrivermanager.version>5.2.1</webdrivermanager.version>
		<junit.version>4.13.2</junit.version>
		<apache.common.version>2.4</apache.common.version>
		<maven.compiler.plugin.version>3.10.1</maven.compiler.plugin.version>
		<maven.surefire.plugin.version>3.0.0-M7</maven.surefire.plugin.version>
		<maven.compiler.source.version>11</maven.compiler.source.version>
		<maven.compiler.target.version>11</maven.compiler.target.version>
	</properties>

	<dependencies>

		<dependency>
			<groupId>io.cucumber</groupId>
			<artifactId>cucumber-java</artifactId>
			<version>${cucumber.version}</version>
		</dependency>

		<dependency>
			<groupId>io.cucumber</groupId>
			<artifactId>cucumber-junit</artifactId>
			<version>${cucumber.version}</version>
			<scope>test</scope>
		</dependency>

		<!-- Selenium -->
		<dependency>
			<groupId>org.seleniumhq.selenium</groupId>
			<artifactId>selenium-java</artifactId>
			<version>${selenium.version}</version>
		</dependency>

		<!-- Web Driver Manager -->
		<dependency>
			<groupId>io.github.bonigarcia</groupId>
			<artifactId>webdrivermanager</artifactId>
			<version>${webdrivermanager.version}</version>
		</dependency>

		<!-- JUnit 4 -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>

		<!-- Apache Common -->
		<dependency>
			<groupId>org.apache.directory.studio</groupId>
			<artifactId>org.apache.commons.io</artifactId>
			<version>${apache.common.version}</version>
		</dependency>

	</dependencies>

Step 8 – Add Maven Compiler Plugin and Surefire Plugin

The compiler plugin is used to compile the source code of a Maven project. This plugin has two goals, which are already bound to specific phases of the default lifecycle:

  • compile – compile main source files
  • testCompile – compile test source files
<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>${maven.compiler.plugin.version}</version>
				<configuration>
					<source>${maven.compiler.source.version}</source>
					<target>${maven.compiler.target.version}</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>${maven.surefire.plugin.version}</version>
				<configuration>
                <includes>
                    <include>**/*Tests.java</include>
                </includes>
				</configuration>
			</plugin>
		</plugins>

The complete POM.xml looks like as shown below

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.example</groupId>
	<artifactId>POM_CucumberJunitDemo</artifactId>
	<version>0.0.1-SNAPSHOT</version>


	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<cucumber.version>7.6.0</cucumber.version>
		<selenium.version>4.3.0</selenium.version>
		<webdrivermanager.version>5.2.1</webdrivermanager.version>
		<junit.version>4.13.2</junit.version>
		<apache.common.version>2.4</apache.common.version>
		<maven.compiler.plugin.version>3.10.1</maven.compiler.plugin.version>
		<maven.surefire.plugin.version>3.0.0-M7</maven.surefire.plugin.version>
		<maven.compiler.source.version>11</maven.compiler.source.version>
		<maven.compiler.target.version>11</maven.compiler.target.version>
	</properties>

	<dependencies>

		<dependency>
			<groupId>io.cucumber</groupId>
			<artifactId>cucumber-java</artifactId>
			<version>${cucumber.version}</version>
		</dependency>

		<dependency>
			<groupId>io.cucumber</groupId>
			<artifactId>cucumber-junit</artifactId>
			<version>${cucumber.version}</version>
			<scope>test</scope>
		</dependency>

		<!-- Selenium -->
		<dependency>
			<groupId>org.seleniumhq.selenium</groupId>
			<artifactId>selenium-java</artifactId>
			<version>${selenium.version}</version>
		</dependency>

		<!-- Web Driver Manager -->
		<dependency>
			<groupId>io.github.bonigarcia</groupId>
			<artifactId>webdrivermanager</artifactId>
			<version>${webdrivermanager.version}</version>
		</dependency>

		<!-- JUnit 4 -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>

		<!-- Apache Common -->
		<dependency>
			<groupId>org.apache.directory.studio</groupId>
			<artifactId>org.apache.commons.io</artifactId>
			<version>${apache.common.version}</version>
		</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>${maven.compiler.plugin.version}</version>
				<configuration>
					<source>${maven.compiler.source.version}</source>
					<target>${maven.compiler.target.version}</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>${maven.surefire.plugin.version}</version>
				<configuration>
                <includes>
                    <include>**/*Tests.java</include>
                </includes>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Step 9 – Create a feature file in the src/test/resources directory

Create a folder with name features. Now, create the feature file in this folder. The feature file should be saved with extension .feature. This feature file contains the test scenarios created to test the application. The Test Scenarios are written in Gherkins language in the format of Given, When, Then, And, But.

Below is an example of Test Scenarios in the feature file. I have failed one test scenario intentionally – @MissingUsername.

Feature: Login to HRM Application 

Background: 
   Given User is on HRMLogin page "https://opensource-demo.orangehrmlive.com/"
 
   @ValidCredentials
   Scenario: Login with valid credentials
     
    When User enters username as "Admin" and password as "admin123"
    Then User should be able to login sucessfully and new page open
    
   @InvalidCredentials
   Scenario Outline: Login with invalid credentials
     
    When User enters username as "<username>" and password as "<password>"
    Then User should be able to see error message "<errorMessage>"
    
  Examples:
  | username   | password  | errorMessage                      |
  | Admin      | admin12$$ | Invalid credentials               |
  | admin$$    | admin123  | Invalid credentials               |
  | abc123     | xyz$$     | Invalid credentials               |
  
  
   @MissingUsername
   Scenario Outline: Login with blank username
     
    When User enters username as " " and password as "admin123"
    Then User should be able to see a message "Required1" below Username
      

Step 10 – Create the classes for locators, actions and utilities in src/main/java

Create a Java Class for each page where define WebElements as variables using Annotation @FindBy . Create another Java class that contains methods for actions performed on WebElements. Here, I’m going to create 2 classes for locators – LoginPageLocators and HomePageLocators.java as well as 2 classes for actions – LoginPageActions and HomePageActions

The Locator class contains WebElements which are identified by @FindBy annotation as shown below:-

@FindBy(name = "txtUsername")
WebElement userName;

Action class contains methods for the action to be performed on the web elements identified in the locator class as shown below:-

public void login(String strUserName, String strPassword) {
 
           // Fill user name
           this.setUserName(strUserName);
 
           // Fill password
           this.setPassword(strPassword);
 
           // Click Login button
           this.clickLogin();
     }
}

The initElements is a static method of PageFactory class that is used to initialize all the web elements located by @FindBy annotation. 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);
     }

Below is the sample code of the LoginPageLocators.

import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

public class LoginPageLocators {

	@FindBy(name = "username")
    public WebElement userName;
 
    @FindBy(name = "password")
    public WebElement password;
    
    @FindBy(xpath = "//*[@id='app']/div[1]/div/div[1]/div/div[2]/div[2]/form/div[1]/div/span")
    public WebElement missingUsernameErrorMessage;
    
    @FindBy(xpath = "//*[@id='app']/div[1]/div/div[1]/div/div[2]/div[2]/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;
       
}

Below is the sample code for the HomePageLocators.

import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

public class HomePageLocators {

	  @FindBy(xpath = "//*[@id='app']/div[1]/div[2]/div[2]/div/div[1]/div[1]/div[1]/h5")
	  public  WebElement homePageUserName;
	  
}

Create the action classes for each web page. These action classes contain all the methods needed by the step definitions. In this case, I have created 2 action classes – LoginPageActionsHomePageActions 

LoginPageActions

import org.openqa.selenium.support.PageFactory;

import com.example.locators.LoginPageLocators;
import com.example.utils.HelperClass;

public class LoginPageActions {

LoginPageLocators loginPageLocators = null; 
	
    public LoginPageActions() {

    	this.loginPageLocators = new LoginPageLocators();

		PageFactory.initElements(HelperClass.getDriver(),loginPageLocators);
	}
 
	// Set user name in textbox
    public void setUserName(String strUserName) {
    	loginPageLocators.userName.sendKeys(strUserName);
    }
 
    // Set password in password textbox
    public void setPassword(String strPassword) {
    	loginPageLocators.password.sendKeys(strPassword);
    }
 
    // Click on login button
    public void clickLogin() {
    	loginPageLocators.login.click();
    }
 
    
   // Get the error message when username is blank
    public String getMissingUsernameText() {
        return loginPageLocators.missingUsernameErrorMessage.getText();
    }
      
    // Get the Error Message
    public String getErrorMessage() {
        return loginPageLocators.errorMessage.getText();
    }
 
    public void login(String strUserName, String strPassword) {
 
        // Fill user name
        this.setUserName(strUserName);
 
        // Fill password
        this.setPassword(strPassword);
 
        // Click Login button
        this.clickLogin();
 
    }
}

HomePageActions

import org.openqa.selenium.support.PageFactory;

import com.example.locators.HomePageLocators;
import com.example.utils.HelperClass;

public class HomePageActions {

	HomePageLocators homePageLocators = null;
    
    public HomePageActions() {
          
        this.homePageLocators = new HomePageLocators();
  
        PageFactory.initElements(HelperClass.getDriver(),homePageLocators);
    }
  
   
    // Get the User name from Home Page
    public String getHomePageText() {
        return homePageLocators.homePageUserName.getText();
    }
  
}

 Create a Helper class where we are initializing the web driver, initializing the web driver wait, defining the timeouts, and creating a private constructor of the class, within it will declare the web driver, so whenever we create an object of this class, a new web browser is invoked. 

import java.time.Duration;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;

public class HelperClass {

	 private static HelperClass helperClass;
     
	    private static WebDriver driver;
	    public final static int TIMEOUT = 10;
	      
	     private HelperClass() {
	           
	        WebDriverManager.chromedriver().setup();
	        driver = new ChromeDriver();
	        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(TIMEOUT));
	        driver.manage().window().maximize();
	     }      
	              
	    public static void openPage(String url) {
	        driver.get(url);
	    }
	  	      
	    public static WebDriver getDriver() {
	        return driver;              
	    }
	      
	    public static void setUpDriver() {
	          
	        if (helperClass==null) {
	              
	            helperClass = new HelperClass();
	        }
	    }
	      
	    public static void tearDown() {
	           
	        if(driver!=null) {
	             driver.close();
	             driver.quit();
	        }
	           
	       helperClass = null;
	   } 
	      
	}

Step 11 – Create a Java Class called Definition where we will create the Test Code related to Given, When, Then of Feature file in src/test/java

Now, we need to create the Step Definition of the Feature File – LoginPageDefinitions.java.

import org.junit.Assert;

import com.example.actions.ForgotPasswordActions;
import com.example.actions.HomePageActions;
import com.example.actions.LoginPageActions;
import com.example.utils.HelperClass;

import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;

public class LoginPageDefinitions {

	LoginPageActions objLogin = new LoginPageActions();
    HomePageActions objHomePage = new HomePageActions();
   
    @Given("User is on HRMLogin page {string}")
    public void loginTest(String url) {
    	
    	HelperClass.openPage(url);
 
    }
 
    @When("User enters username as {string} and password as {string}")
    public void goToHomePage(String userName, String passWord) {
 
        // login to application
        objLogin.login(userName, passWord);
 
        // go the next page
        
    }
    
    @Then("User should be able to login sucessfully and new page open")
    public void verifyLogin() {
 
        // Verify home page
        Assert.assertTrue(objHomePage.getHomePageText().contains("Employee Information"));
 
    }
    
    @Then("User should be able to see error message {string}")
    public void verifyErrorMessage(String expectedErrorMessage) {
 
        // Verify home page
    	Assert.assertEquals(objLogin.getErrorMessage(),expectedErrorMessage);
 
    }
    
    @Then("User should be able to see a message {string} below Username")
    public void verifyMissingUsernameMessage(String message) {
    	
    	Assert.assertEquals(objLogin.getMissingUsernameText(),message);
    }
      
}

Step 12 – Create a Hook class to contain the initialization and closing of browser in src/test/java

Create the hook class that contains the Before and After hook to initialize the web browser and close the web browser. I have added the code to take the screenshot of the failed scenario in @After Hook.

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;

import com.example.utils.HelperClass;

import io.cucumber.java.After;
import io.cucumber.java.Before;
import io.cucumber.java.Scenario;

public class Hooks {

	@Before
    public static void setUp() {

       HelperClass.setUpDriver();
    }

	@After
	public static void tearDown(Scenario scenario) {

		//validate if scenario has failed
		if(scenario.isFailed()) {
			final byte[] screenshot = ((TakesScreenshot) HelperClass.getDriver()).getScreenshotAs(OutputType.BYTES);
			scenario.attach(screenshot, "image/png", scenario.getName()); 
		}	
		
		HelperClass.tearDown();
	}
}

Step 13 – Create a JUnit Cucumber Runner class to execute the test scenarios in the src/test/java directory

Cucumber needs a TestRunner class to run the feature files. It is suggested to create a folder with the name of the runner in the src/test/java directory and create the Cucumber TestRunner class in this folder. Below is the code of the Cucumber TestRunner class.

import org.junit.runner.RunWith;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;

@RunWith(Cucumber.class)
@CucumberOptions(tags = "", features = "src/test/resources/features/LoginPage.feature", glue = "com.example.definitions",
                 plugin = {})
   
public class CucumberRunnerTests {
   
}

Note:- The name of the Runner class should end with Test otherwise we can’t run the tests using Command Line.

Step 14 – Run the tests from JUnit

You can execute the test script by right-clicking on TestRunner class -> Run As JUnit.

Step 15 – Run the tests from Command Line

Run the below command in the command prompt to run the tests and to get the test execution report.

mvn clean test

Step 16 – Cucumber Report Generation

To get Cucumber Test Reports, add cucumber.properties under src/test/resources and add the below instruction in the file.

cucumber.publish.enabled=true

Below is the image of the Cucumber Report generated using Cucumber Service.

In the above example, as we can see, one of the tests has failed. So, when a test fails, we have written the code to take a screenshot of the failed step. The highlighted box above shows the image of the failed test. You can click on that to see the screenshot.

That’s it! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

How to Download and Install Eclipse IDE

HOME

 Eclipse IDE is a software that allows you to write your programs and test scripts in multiple programming languages (with Java being the most popular one).

Download Eclipse IDE

 1. Open the below mentioned link. Latest version of Eclipse available is Eclipse IDE 2020-09 R Packages  Eclipse Download .

       
 2. Select – Eclipse IDE for Java Developers. Depending on type of Operating System, download either 32 bit or 64 bit. My system is 64 bit, so downloading 64 bit Eclipse .

3. Click on Download button to start downloading process.

Install/Setup Eclipse

  1.  We do not need to install Eclipse, just unzip the Eclipse downloaded folder. Go to the path where Eclipse downloaded and unzip the folder .

2.    Eclipse folder have Eclipse Editor (Eclipse.exe), double click on it.

3.   Eclipse Workplace directory will get open. You can provide name to this directory. In Eclipse, all the projects saved in Eclipse Directory

4.  A folder with same Eclipse Directory name creates in same path as mentioned above.

5.  There are chances that you may face the issue while trying to access Eclipse IDE – Java was started but returned exit code =13. This is because there is configuration mistake in Eclipse.ini (Eclipse Configuration) file. The error will look like something below:-

To fix this issue, open the Eclipse Configuration file. It will be present in unzipped Eclipse Folder. 

Add the below mentioned line in Eclipse Configuration file:-

             -vm
                   C:\Program Files\Java\jre1.8.0_201\bin\java.exe

 More details can found from below link                                  

https://wiki.eclipse.org/Eclipse.ini#Specifying_the_JVM

Maven Tutorials

 HOME

 

Apache Maven is a software project management and comprehension tool. Based on the concept of a project object model (POM), Maven can manage a project’s build, reporting and documentation from a central piece of information. Maven is a part of the Apache Software Foundation.

Maven Installation

 Chapter 1 Maven – How to install Maven on Window

Eclipse IDE

Chapter 1 Maven – How to create a Java project using Command Line
Chapter 2 Maven – How to create Maven project in Selenium
Chapter 3 Maven – How to import Maven project in Eclipse
Chapter 4 Maven – How to add M2_REPO classpath variable to Eclipse

IntelliJ IDE

Chapter 1 How to create Maven project in IntelliJ
Chapter 2 How to import Java Maven project in IntelliJ
Chapter 3 How to create a Java Maven project using Command Line in IntelliJ

Java Tutorials

Java is a general-purpose programming language that is a concurrent, class-based, and object-oriented language. Java follows the concept of “write once and run anywhere (WORA)” which means that compiled Java code can be run on all different platforms that support Java without the need for recompilation.

Eclipse IDE

Chapter 1 How to Download and Install Eclipse IDE
Chapter 2 How to Clone a project from GitLab using Eclipse
Chapter 3 How to Export Eclipse projects to GitLab

IntelliJ IDE

Chapter 1 How to install IntelliJ on Windows
Chapter 2 How to create a Java project in IntelliJ
Chapter 3 How to Clone a project from GitLab using IntelliJ
Chapter 4 How to Export IntelliJ project to GitLab

Basics of Java

Chapter 1 How to Download & Install Java JDK 11 in Windows
Chapter 2 Data Types and Operators in Java
Chapter 3 Decision Making in Java – If, If Else, Switch, Break, Continue
Chapter 4 Loop Control Statements in Java – For, While, Do While, Enhanched For Loop
Chapter 5 String Manipulation
Chapter 6 Difference between == and equals() method in Java
Chapter 7 Arrays in Java
Chapter 8 Access Modifiers in Java
Chapter 9 ArrayList in Java
Chapter 10 Methods in Java
Chapter 11 Method Overloading in Java
Chapter 12 Constructors in Java   
Chapter 13 This Keyword in Java   
Chapter 14 Static Keyword – Static Variable and Static Method in Java
Chapter 15 Difference between Static Method and Non-Static Method
Chapter 16 How to use Java Lambda expression to create thread via Runnable function
Chapter 17 runAsync and supplyAsync in ComputableFuture in Java8
Chapter 18 HashMap in Java
Chapter 19 Iterators in Java

OOPs Concepts

Chapter 1 Class and Object in Java
Chapter 2 Inheritance in Java
Chapter 3 Encapsulation in Java
Chapter 4 Polymorphism in Java
Chapter 5 Abstraction in Java
Chapter 6 Interface in Java
Chapter 7 Difference between Abstract Class and Interface

Exceptions in Java

Chapter 1 Exception Handling in Java
Chapter 2 Types of Exception in Java
Chapter 3 Flow control in try catch finally in Java
Chapter 4 Multiple Catch Exceptions
Chapter 5 Throw in Java
Chapter 6 Throws in Java

Data Handling (Excel Manipulation)

Chapter 1 How to download and install Apache POI
Chapter 2 How to read Excel in Java
Chapter 3 How to write data in Excel in Java
Chapter 4 How to update existing excel in Java
Chapter 5 How to add Formulas in Excel in Java

Multiple Choice Questions

Chapter 1 Multiple questions on Exception Handling in Java

Java Library

Chapter 1 AssertJ – Fluent Assertions in Java