Page Object Model with Selenium, Cucumber, and TestNG

HOME

In the previous tutorial, I explained the Page Object Model with Selenium, Cucumber and JUnit. In this tutorial, I’ll create a BDD Framework for the testing of web applications using the Page Object Model with Selenium, Cucumber, and TestNG.

This framework consists of

  1. Cucumber Java – 7.11.1
  2. Cucumber TestNG – 7.11.1
  3. Java 11
  4. Maven – 3.8.6
  5. Selenium – 4.3.0
  6. TestNG – 7.7.1

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. Setup Maven on System
  3. Install Cucumber Eclipse Plugin (Only for Eclipse IDE)
  4. Create a new Maven Project
  5. Create a source folder – src/test/resources to create test scenarios in the Feature file
  6. Add Selenium, Cucumber and JUnit4 dependencies to the project
  7. Add Maven Compiler Plugin and Surefire Plugin
  8. Create a feature file under src/test/resources
  9. Create the classes for locators, actions, and utilities in src/main/java
  10. Create a StepDefinition class in src/test/java
  11. Create a Hook class in src/test/java
  12. Create a Cucumber Runner class in the src/test/java directory
  13. Run the tests from TestNG
  14. Run the tests from testng.xml
  15. Run the tests from Command Line
  16. Cucumber Report Generation
  17. TestNG 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 – 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 3 – Install Cucumber Eclipse Plugin (Only for Eclipse)

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 4 – 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 5 – 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 test directory ->select New ->Directory, and then it shows Maven Source Directories as resources as shown below.

Double-click on the resources directory and a new source directory under your new Maven project is created as shown in the below image.

Step 6 – Add Selenium, TestNG, and Cucumber dependencies to the project

Add below mentioned Selenium, TestNG, 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>
        <cucumber.version>7.11.1</cucumber.version>
        <selenium.version>4.3.0</selenium.version>
        <webdrivermanager.version>5.2.1</webdrivermanager.version>
        <testng.version>7.7.1</testng.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>

        <!-- Cucumber with Java Dependency -->
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>${cucumber.version}</version>
        </dependency>

        <!-- Cucumber with TestNG Dependency -->
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-testng</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>

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

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

        <!-- TestNG Dependency -->
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>${testng.version}</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

Step 7 – 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

<?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>org.example</groupId>
    <artifactId>POM_CucumberTestNG_Demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <cucumber.version>7.11.1</cucumber.version>
        <selenium.version>4.3.0</selenium.version>
        <webdrivermanager.version>5.2.1</webdrivermanager.version>
        <testng.version>7.7.1</testng.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>

        <!-- Cucumber with Java Dependency -->
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>${cucumber.version}</version>
        </dependency>

        <!-- Cucumber with TestNG Dependency -->
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-testng</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>

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

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

        <!-- TestNG Dependency -->
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>${testng.version}</version>
            <scope>test</scope>
        </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 8 – Create a feature file in the src/test/resources

Create a folder with name features. Now, create the feature file in this folder. The feature file should be saved with the 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: 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 9 – Create the classes for locators, actions, and utilities in src/main/java

Create folders – actions, locators, and utils 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 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.

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[1]/header/div[1]/div[1]/span/h6")
    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.example.locators.LoginPageLocators;
import org.example.utils.HelperClass;
import org.openqa.selenium.support.PageFactory;

public class LoginPageActions {

    LoginPageLocators loginPageLocators = null;

    public LoginPageActions() {

        this.loginPageLocators = new LoginPageLocators();

        PageFactory.initElements(HelperClass.getDriver(),loginPageLocators);
    }

    // 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
        loginPageLocators.userName.sendKeys(strUserName);

        // Fill password
        loginPageLocators.password.sendKeys(strPassword);

        // Click Login button
        loginPageLocators.login.click();

    }

HomePageActions

import org.example.locators.HomePageLocators;
import org.example.utils.HelperClass;
import org.openqa.selenium.support.PageFactory;

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, 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 10 – Create a StepDefinition class in src/test/java

Create a Java Class called Definition where we will create the Test Code related to the 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 io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.example.actions.HomePageActions;
import org.example.actions.LoginPageActions;
import org.example.utils.HelperClass;
import org.testng.Assert;

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 successfully and new page open")
    public void verifyLogin() {

        // Verify home page
        Assert.assertTrue(objHomePage.getHomePageText().contains("Dashboard"));

    }

    @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 11 – Create a Hook class 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.

Below is the code for the Hooks class.

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 12 – Create a JUnit Cucumber Runner class in the src/test/java

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.

Below is the code for CucumberRunnerTests class.

import io.cucumber.testng.AbstractTestNGCucumberTests;
import io.cucumber.testng.CucumberOptions;

@CucumberOptions(tags = "", features = "src/test/resources/features/LoginPage.feature", glue = "org.example.definitions",
        plugin = {})

public class CucumberRunnerTests extends AbstractTestNGCucumberTests {
}

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

Step 13 – Run the tests from TestNG

You can execute the test script by right-clicking on TestRunner class -> Run As TestNG. (Eclipse)

In the case of the IntelliJ project, right-click on the runner class and select Run ‘CucumberRunnerTests’.

The output of the above program is

Step 14 – Run the tests from testng.xml

Create a TestNG.xml as shown below and run the tests as TestNG.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite">
    <test  name="Cucumber with TestNG Test">
        <classes>
            <class name="org.example.runner.CucumberRunnerTests"/>
        </classes>
    </test> <!-- Test -->
</suite> <!-- Suite -->

The testng.xml is highlighted below:

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

The output of the above program is

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 the 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 Attached Image shows the image of the failed test. You can click on that to see the screenshot.

Step 17 – TestNG Report Generation

TestNG generates various types of reports under the target->surefire-reports folder like emailable-report.html, index.html, testng-results.xml.

We are interested in the “emailable-report.html” report. Open “emailable-report.html“, as this is an HTML report, and open it with the browser. The below image shows emailable-report.html.

emailable-report.html

Index.html

TestNG also produces an “index.html” report. The below image shows the index.html report.

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

Advertisement

How to configure Junit in Intellij

HOME

In this tutorial we will discuss to create a JUnit  project using IntelliJ. We will be at first creating a simple Java Project and will add JUnit5 as well as create a Maven Project, then we will add a basic Class and a JUnit Test for it.

Java Project

Step 1 – Create a new Java Project.

To create a new Java project in Intellij, please refer to this tutorial.

Step 2 – Right click on the project and select Open Module Settings.

Step 3 – Go to the “Libraries” group, click the little plus (look up), and choose “From Maven…” option.

Step 4 – Search for “junit” — something like “junit:junit-4.13“. Click the “OK” button.

Step 5 – A new dialog will appear to confirm that “junit:junit:4.13.2” will be added to the module. Click the “OK” button.

Step 6 – This screens shows that junit:junit:4.13.2 is added to the Libraries. It contains the highlighted classes – junit-4.13.2.jar and hamcrest-core-1.3.jar. Click the “OK” button.

Step 7 – This image shows that the Junit is added to the External Libraries.

Step 8 – Create a Java Class – JUnit4Test under src and create a JUnit test to verify that it is installed properly.

import org.junit.Assert;
import org.junit.Test;

public class JUnit4Test {

    @Test
    public void Test() {

        String str1 = "Happy";
        String str2 = new String("Happy");
        Assert.assertEquals("String1 and String 2 are equal",str1, str2);

    }
}

Step 9 – There are many ways to run the test. One of the way is to Right-Click and select Run JUnit4Test

The successful execution of the test shows that the JUnit is configured properly.

Maven Project

Add Junit dependency to the POM.xml and build the project.

<dependencies>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.2</version>
        <scope>test</scope>
    </dependency>
    
</dependencies>

Now we need to apply the changes in the build script. Press Ctrl+Shift+O or click Load Maven Changes in the notification that appears in the top-right corner of the editor.

Create a Java Class – JUnit4Test under src/test/java and create a JUnit test to verify that it is installed properly.

import org.junit.Test;

import static org.junit.Assert.assertArrayEquals;

public class JUnitMavenTest {

    @Test
    public void Test() {

        String[] expected = {"happy","days","summer","spring"};
        String[] actual = {"happy","days","summer","spring"};

        assertArrayEquals("Expected and Actual Arrays are not equal",expected,actual);

    }
}

Similarly, to add JUnit5 we can add below mentioned dependencies to the POM.xml.

<dependency>
     <groupId>org.junit.jupiter</groupId>
     <artifactId>junit-jupiter-engine</artifactId>
     <version>5.8.2</version>
     <scope>test</scope>
</dependency>

<dependency>
     <groupId>org.junit.jupiter</groupId>
     <artifactId>junit-jupiter-api</artifactId>
     <version>5.8.2</version>
     <scope>test</scope>
</dependency>

Congratulations. We are able to add JUnit to Java or Maven project. Happy Learning!!

JUnit Tutorials

HOME

JUnit is an open source Unit Testing Framework for JAVA.
JUnit is a simple framework to write repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks.

JUnit4

Chapter 1 How to configure Junit in Intellij
Chapter 2 How to run JUnit5 tests through Command Line
Chapter 3 JUnit4 Assertions
Chapter 4 How to Parameterize tests in JUnit4
Chapter 5 How to generate JUnit4 Report
Chapter 6 Integration of Cucumber with Selenium and JUnit
Chapter 7 Integration of Serenity with Cucumber6 and JUnit5
Chapter 8 Integration of Serenity with JUnit4
Chapter 9 Rest API Test in Cucumber BDD
Chapter 10 Difference between JUnit4 and JUnit5

JUnit5

Chapter 1 JUnit5 Assertions Example
Chapter 2 Grouped Assertions in JUnit 5 – assertAll()
Chapter 3 How to Retry Test in JUnit5 – @RepeatedTest
Chapter 4 How to disable tests in JUnit5 – @Disabled
Chapter 5 How to run JUnit5 tests in order
Chapter 6 How to tag and filter JUnit5 tests – @Tag
Chapter 7 Assumptions in JUnit5
Chapter 8 How to parameterized Tests in JUnit5
Chapter 9 How to run parameterized Selenium test using JUnit5
Chapter 10 Integration of Serenity with JUnit5
Chapter 11 Integration of Serenity with Cucumber6 and JUnit5

Gradle

Chapter 1 Gradle – Allure Report for Selenium and JUnit4
Chapter 2 Gradle Project with Cucumber, Selenium and JUnit4
Chapter 3 Gradle – Integration of Selenium and JUnit5

Create your first SpringBoot application in IntelliJ

HOME

This tutorial describes how to create and run a Spring application in IntelliJ IDEA. For this purpose, we need IntelliJ IDEA Ultimate Version. The Ultimate edition is commercial version (which has trial version for 30 days post which you needs license).

IntelliJ Ultimate will create a Spring Boot Maven project generated by Spring Initializr. This is the quickest way to create a Spring application, and IntelliJ IDEA provides a dedicated project wizard for it.

Steps to create a new Spring Boot project

Step 1 – From the main menu, select File -> New -> Project.

Step 2 – In the left pane of the New Project wizard, select Spring Initializr.

From the Project SDK list, select the JDK that you want to use in the project. I have used – 11 Amazon Corretto version 11.0.10.

If the JDK is installed on your computer, but not defined in the IDE, select Add JDK and specify the path to the JDK home directory.

If you don’t have the necessary JDK on your computer, please Download JDK from here.

To check if you have Java installed on your machine or not, please use the below command in command prompt.

java -version

This shows that Java 11 is already installed on my machine.

Step 3 – Select the default https://start.spring.io/ service and click the Next button.

Step 4 – Mention the Group and Artifact name. Other Information is auto populated. Change them, if you want something different than already mentioned. Click the Next button.

Step 5 – Select the Spring Web dependency under Web and click the Next button. I have used this combination because I want to create a RESTful application using Apache Tomcat.

Step 6 – A new window appears where mention the location where you want to save the new project. I have created a folder springbootdemo and save the project files in that folder.

Step 7 – Below is the structure of new project on local machine

Step 8 – This is how the project looks in IntelliJ.

Spring Initializr generates a valid project structure with the following files:

  1. A build configuration file – pom.xml for Maven.
  2. A class with the main() method to bootstrap the application – SpringbootdemoApplication.
  3. An empty JUnit test class – SpringbootdemoApplicationTests.
  4. An empty Spring application configuration file – application.properties.

Step 9 – To run the application, Right click on the SpringbootdemoApplication.java class and select Run SpringbootdemoApplication

The springbootdemoApplication is started and this is the image of the execution screen.

The POM.xml created is as shown below.

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>springbootdemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springbootdemo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

How to Export IntelliJ project to GitLab

HOME

What is GitLab?

GitLab is the open DevOps platform, delivered as a single application that spans the entire software development lifecycle. If you’re not using GitLab, your DevOps lifecycle is likely spread across any number of applications. These silos take overhead to integrate, manage, configure, and maintain, slowing down your team and your deployments. Moving to a single application will speed up your workflow and help you deliver better software, faster. To know more about GitLab, click here.

In this article, we will see how to push an existing project to GitLab using Eclipse IDE.

Implementation Steps

Step 1 – Go to Git at the top, select VCS ->VCS Oprations -> Create Git Repository.

This will convert the project to a Git project.

Step 2 – Go to Git option present at the top and then select “Commit” option.

Step 3 – This will show all the files which are uncommitted. Select the files you want to commit and mention a message in the below message box as “New project from IntelliJ to GitLab“. Click on the Commit button.

Step 4 – A window opens where we need to mention the location where the project should be pushed in GitLab.

Click the OK button. It will ask for credentials to the GitLab, provide them.

Step 5 – The below image shows that the latest code is moved to GitLab. Here, the origin branch is used to commit and pushed the changes. If we are using a local branch to commit and push the changes, then we need to create a merge request to merge the code of the new branch to the code of existing origin(master branch).

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

How to Clone a project from GitLab using IntelliJ

HOME

What is GitLab?

GitLab is a web-based Git repository that provides free open and private repositories, issue-following capabilities, and wikis. It is a complete DevOps platform that enables professionals to perform all the tasks in a project—from project planning and source code management to monitoring and security.

Why Use GitLab?

The primary advantage of using GitLab is that it allows all team members to collaborate at all stages of the project. GitLab provides tracking from planning to creation to assist developers in automating the entire DevOps lifecycle and achieving the best results possible. GitLab is becoming increasingly popular among developers due to its extensive set of features and codes building blocks.

In this tutorial, I will explain how we can clone a project from GitLab in IntelliJ.

Implementation Steps

Step 1 – Go to GitLab and select the project which you want to clone. Click on the blue color “Clone” button, then copy the hyperlink as shown in the image. You can either Clone with SSH or Clone with HTTPS.

Step 2 – From the main menu, select Git -> Clone

Another way is File ->New -> Project from Version Control

Step 3 – In the Get from Version Control dialog, specify the URL of the remote repository you want to clone. This is retrieved from Step 1. Click the Clone button.

Step 4 – A dialog box will appear to log in to GitLab. Provide the username and password of GitLab. Select the “Log In” button.

Step 5 – When you import or clone a project for the first time, IntelliJ IDEA analyses it. If the IDE detects more than one configuration (for example, Eclipse and Gradle), it prompts you to select which configuration you want to use. Select the necessary configuration and click the OK button. I have selected the Maven project.

Step 6 – Once I have selected the Maven project, a new dialog box will appear. IntelliJ asks you to either Trust the Project or Preview it in Safe Mode. I trust the project, so I have selected the Trust Project button.

Step 7 – IntelliJ will ask if you want to open the project in the current window or New Window. It is always a good practice to open the project in a New Window.

Step 8 – We have successfully imported the GitLab Repository as shown in the below image.

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

How to create Gradle Java project in IntelliJ 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 in IntelliJ.

Implementation Steps

Step 1- Create a Project Folder and change the directory path to the folder where we want to save the latest files created post creation of the project. Here, I have created a folder – GradleIntelliJDemoFromCMD and changed the directory path.

cd C:\Users\Vibha\Projects\Vibha_Personal\GradleIntelliJDemoFromCMD

Step 2 – Open the Terminal in IntelliJ.

Step 3 – Gradle comes with a built-in task, called init , that initializes a new Gradle project in an empty folder. The init task uses the (also built-in) wrapper task to create a Gradle wrapper script, gradlew. Type the below command and press ENTER.

Step 4 – 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 5 – Select implementation language. This is a Java project, so TYPE 3 (Java) 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 – GradleIntelliJDemoFromCMD
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 – The project is created and placed under the folder GradleIntelliJDemoFromCMD as shown below.

This project structure will have below mentioned files:-

  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

That’s it. We are done.

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

How to import Java Gradle project in IntelliJ

HOME

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

Steps to follow:-

Step 1 – Open IntelliJ IDEA and Welcome Screen appears. Click the Open button present on Welcome Screen.

Step 2 – Navigate to your Gradle project and select the top-level folder. Select the project you want to Import. Select the OK button to proceed to the next screen.

Step 3 – A screen appears to Open or Import project. It will have all the possible configurations for the project. As this is a Gradle project, select  Gradle project and click the OK Button.

Step 4 – A warning message box will appear. Select Trust Project button and move forward.

Step 5 – The imported project structure in IntelliJ is shown below.

Step 6 – This screen shows that the project is imported and build successfully.

Step 7 – This screen shows the build.gradle of the imported project.

Step 8 – Run the test present in the project. Here, I have run App. Right-click on App ->Run ‘App.main()’. The below screen shows that the project is imported successfully.

That’s it! We are done!!!

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!!