How to Export Eclipse projects 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 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 – Open Eclipse IDE and right-click on the project you want to push and go to the Team ->Share project.

Step 3 – It will add the project to the given repository as shown below image. Select the Finish button.

As you can see, the given project is Git Repository. If the project is not GIT Repository, refer to this tutorial – How to create a new Git Repository  to convert the project in GIT Repository.

Step 4 – Again, Right-Click on the project and go to the Team ->commit.

Step 5 – Select the files you want to commit and click green color + sign or Drag and Drop the files from Unstaged Changes to Staged Changes.

This is how the stage files looks like as shown below.

Step 6 – Write the commit message in “Commit Message” and click “Commit and Push“.

Step 7 – Fill in the below details in this window and click the “Preview” button.

URI – This is the URL that we have cloned from GitLab in Step 1.
Host – gitlab.com
Repository path – the path of the project in GitLab (This is auto-populated after entering URI)

Authentication
User – Username of GitLab
Password – password of GitLab

Step 8 – A new window will open which provides the detail of the Destination location of the project. Click the “Preview” button.

Step 9 – Push to the new branch of GitLab Repository and click the Push button.

Step 10 – As this is a new project with a master branch, you can see the whole project migrated in GitLab. If we are not using the master branch, but the local branch, then we need to create a merge request to merge the latest changes in the already existing project in GitLab.

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

Run Gradle Cucumber Tests from Command Line

HOME

The implementation of a test framework is considered successful and effective, if the test framework supports test execution in multiple ways.
The tests in a Gradle Cucumber Framework can be executed as JUnit Tests, Gradle Tests and Gradle commands from Command Line.

In this tutorial, I will explain to run Gradle tests from Command Line.

To execute tests using JUnit Tests and Gradle Tests, we need to create a JUnit TestRunner.

Steps to follow

  1. Create a Gradle Java Project.
  2. Add Rest-Assured and Cucumber dependencies to the Gradle project
  3. Add Configuration to build.gradle
  4. Add Gradle Cucumber Task to build.gradle
  5. Create a feature file under src/test/resources
  6. Create the Step Definition class or Glue Code for the Test Scenario
  7. Run the tests from Command Line

Step 1 – Create a Gradle project

Step 2 – Add the below mention dependencies in the Gradle project in build.gradle.

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()
    mavenCentral()
}

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'
    testImplementation 'io.cucumber:cucumber-java:6.6.1'
    testImplementation 'io.cucumber:cucumber-junit:6.6.1'
    testImplementation 'io.rest-assured:rest-assured:4.3.3'
}

Step 3Add Configuration to build.gradle

configurations {
    cucumberRuntime {
        extendsFrom testImplementation
    }
}

Step 4Add Gradle Cucumber Task to build.gradle

task cucumber() {
    dependsOn assemble, testClasses
    doLast {
        javaexec {
            main = "io.cucumber.core.cli.Main"
            classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
            args = ['--plugin', 'pretty','--glue', 'Cucumber_Gradle_Demo.definitions', 'src/test/resources']
        }
    }
}

task getexample() {
    dependsOn assemble, compileTestJava
    doLast {
        javaexec {
            main = "io.cucumber.core.cli.Main"
            classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
            args = ['--plugin', 'pretty', '--glue', 'Cucumber_Gradle_Demo.definitions', 'src/test/resources/features/', '--tags', '@getexample']
        }
    }
}

task postexample() {
    dependsOn assemble, compileTestJava
    doLast {
        javaexec {
            main = "io.cucumber.core.cli.Main"
            classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
            args = ['--plugin', 'pretty', '--glue', 'Cucumber_Gradle_Demo.definitions', 'src/test/resources/features/', '--tags', '@postexample']
        }
    }
}

Here, task cucumber will execute all the tests present in the project irrespective of the number of feature files and scenarios within the feature file.

Step 5 Create a feature file under src/test/resources

I have created 2 sample feature files – API_GetExample.feature and API_PostExample.feature.

Below is the API_GetExample.feature

@getexample
Feature: Validation of get method
 
  @GetUserDetails
  Scenario Outline: Send a valid Request to get user details
 
  Given I send a request to the URL to get user details
  Then the response will return status 200 and id <id> and salary <employee_salary> and name "<employee_name>" and age <employee_age> and message "<message>"
 
Examples:
    |id  |employee_salary|employee_name |employee_age  |message                                  |
    |1   |320800         |Tiger Nixon   |61            |Successfully! Record has been fetched.   |
    
      
  @GetAllUsers    
  Scenario Outline: Send a valid Request to get the details of all the users
 
  Given I send a request to the URL to get the details of all the users
  Then the response will return status 200 and message "<message>"
 
Examples:
      |message                                  |
      | Successfully! All records has been fetched.   |

API_PostExample.feature

@postexample
Feature: Validation of POST method
 
  @CreateUser
  Scenario Outline: Send Request to create a user
 
  Given I send a request to the URL to create a new user
  Then the response will return status 200 and name "<employee_name>" and message "<message>"
 
Examples:
    |employee_name |message                                |
    |posttest      |Successfully! Record has been added.   |

Run Test from Command Line

1. Open the command prompt and change directory to the project location .

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

2. All feature files should be in src/test/resources and create Cucumber Runner class as CucumberRunnerTest.
Note:- The Runner class name should end with Test to execute the tests from Command Line

Running all Feature files or Tests from Command Line

Below command will run all the tests present in the project. As you can see, there are 2 feature files – API_GetExample.feature contains 2 scenarios and API_PostExample.feature contains 1 scenario.

gradle cucumber

Below screenshot shows that Task : Cucumber is triggered.

Below screenshot shows that tests are executed and the status of the tests.

Running a Feature file from Command Line

To run a particular feature, create a task – postexample for that feature in the build.gradle as shown in the below example.

task postexample() {
    dependsOn assemble, compileTestJava
    doLast {
        javaexec {
            main = "io.cucumber.core.cli.Main"
            classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
            args = ['--plugin', 'pretty', '--glue', 'Cucumber_Gradle_Demo.definitions', 'src/test/resources/features/', '--tags', '@postexample']
        }
    }
}

Add this task as a feature tag name and the use it to run the test of that particular feature file.

@postexample
Feature: Validation of POST method

Use the below command to run the tests of API_PostExample.feature.

gradle postexample

Running Scenarios using Tags from Command Line

To execute the tests using tags, we need to add ‘–tags’, “${tags}” in build.gradle

task cucumber() {
    dependsOn assemble, testClasses
    doLast {
        javaexec {
            main = "io.cucumber.core.cli.Main"
            classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
            args = ['--plugin', 'pretty','--tags', "${tags}",'--glue', 'Cucumber_Gradle_Demo.definitions', 'src/test/resources']
        }
    }
}

Use the below mentioned command to run the tests tagged with tag = GetUserDetails.

gradle cucumber -P tags=@GetUserDetails

Page Object Model without Page Factory in Selenium Webdriver

HOME

What is Page Object Model?

Page Object Model(POM) is an object design pattern in Selenium webdriver which tells how to organize the object repository. In this case, we refer to web elements as Objects. Page Object Model(POM) is not a Test Framework.

In the Page Object Model (POM), each web page is represented as a separate class. For example, consider HRM website. It has many web pages like Login , Dashboard , Assign Leave, Leave List, Timesheets, etc. Under this model, for each web page in the application, there should be a corresponding Page Class. This Page class will identify the WebElements of that web page and also contains Page methods that perform operations on those WebElements.

If a new web element is added or an existing web element is updated, then you can add or update that web element in object repository by navigating to class which has same name as webpage.

The object repository is independent of test cases, so we can use the same object repository for a different purpose with different tools. For example, we can integrate Page Object Model in Selenium with TestNG/JUnit for functional Testing and at the same time with JBehave/Cucumber for acceptance testing.

POM enhances test maintenance, readability and reducing code duplication.

In this tutorial, I’m creating a project using Page Object Model as Design Pattern and TestNG as the Test Automation Framework.

Steps to create a Page Object Model Project

  1. Download and Install Java on system
  2. Download and setup Eclipse IDE on system
  3. Setup Maven
  4. Create a new Maven Project
  5. Add dependencies to pom.xml
  6. Create Page Class for each page – LoginPage.Java and DashboardPage.java
  7. Create tests for each Page – BaseTests, LoginTests and DashboardTests
  8. Create a TestNG.XML
  9. Run the tests from TestNG.xml
  10. TestNG Report Generation

Step 1- Download and Install Java

Click here to know How to install Java. To check if Java is already installed on your machine, use the below command in the command line. This command will show the version of Java installed on your machine.

java -version

Step 2 – Download and setup Eclipse IDE on system

The Eclipse IDE (integrated development environment) provides strong support for Java developer. The Eclipse IDE for Java Developers distribution is designed to support standard Java development. It includes support for the Maven and Gradle build system and support for the Git version control system. 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. It is very tedious and cumbersome process to add each dependency manually. So, to overcome this problem, we use a build management tool. Maven is a build management tool which is used to define project structure, dependencies, build, and test management. Click here to know How to install Maven.

To know if Maven is already installed or not on your machine, type this command in the command line. This command will show the version of Maven installed on your machine.

mvn -version

Step 4 – Create a new Maven Project

Click here to know How to create a Maven project

Below is the Maven project structure. Here,

Group Id – com.example
Artifact Id – pageobjectmodel_demo
Version – 0.0.1-SNAPSHOT
Package – com. example.pageobjectmodel_demo

Step 5 – Add dependencies to the pom.xml

I have added Selenium and TestNG dependencies.

<dependencies>
  
   <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>3.141.59</version>
    </dependency>
    
    <!-- https://mvnrepository.com/artifact/org.testng/testng -->
    <dependency>
      <groupId>org.testng</groupId>
      <artifactId>testng</artifactId>
      <version>7.4.0</version>
      <scope>test</scope>
    </dependency>   
    
</dependencies>

Step 6 – Create Page Class for each page – LoginPage.Java and DashboardPage.java

I want to test 2 pages – Login and Dashboard. So, I’m creating 2 seperate class. Each class will contain its web elements and methods of that page.

LoginPage.Java

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class LoginPage {

	WebDriver driver;

	By userName = By.name("txtUsername");

	By password = By.name("txtPassword");

	By titleText = By.id("logInPanelHeading");

	By login = By.id("btnLogin");

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

	// Set user name in textbox
	public void setUserName(String strUserName) {
		driver.findElement(userName).sendKeys(strUserName);
	}

	// Set password in password textbox
	public void setPassword(String strPassword) {
		driver.findElement(password).sendKeys(strPassword);
	}

	// Click on login button
	public void clickLogin() {
		driver.findElement(login).click();
	}

	// Get the title of Login Page
	public String getLoginTitle() {
		return driver.findElement(titleText).getText();
	}

	public void login(String strUserName, String strPasword) {

		// Fill user name
		this.setUserName(strUserName);

		// Fill password
		this.setPassword(strPasword);

		// Click Login button
		this.clickLogin();
	}
}

DashboardPage.java

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class DashboardPage {

	WebDriver driver;

	By homePageUserName = By.id("welcome");

	public DashboardPage(WebDriver driver) {
		this.driver = driver;

	}

	// Get the User name from Home Page
	public String getHomePageText() {
		return driver.findElement(homePageUserName).getText();
	}

}

Step 7 – Create tests for each Page – BaseTests, LoginTests and DashboardTests

Here, I have created 3 classes. BaseTest class to contain startUp and tearDown methods. These methods will run once before the after of every class. LoginTests and DashboardTests classes contain the tests related to LoginPage and DashboardPage respectively.

BaseTest

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;

import com.example.pageobjectmodel_demo.pages.DashboardPage;
import com.example.pageobjectmodel_demo.pages.LoginPage;

public class BaseTest {

	public static WebDriver driver;
	LoginPage objLogin;
	DashboardPage objDashboardPage;

	@BeforeClass
	public void setup() {
		System.setProperty("webdriver.gecko.driver",
				"C:\\Users\\Vibha\\Software\\geckodriver-v0.26.0-win64\\geckodriver.exe");
		driver = new FirefoxDriver();
		driver.manage().window().maximize();
		driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
		driver.get("https://opensource-demo.orangehrmlive.com/");
	}

	@AfterClass
	public void close() {
		driver.close();
	}
}

LoginTests

import org.testng.Assert;
import org.testng.annotations.Test;

import com.example.pageobjectmodel_demo.pages.DashboardPage;
import com.example.pageobjectmodel_demo.pages.LoginPage;

public class LoginTests extends BaseTest {

	LoginPage objLogin;
	DashboardPage objDashboardPage;

	@Test(priority = 0)
	public void loginTest() {

		// Create Login Page object
		objLogin = new LoginPage(driver);

		// Verify login page text
		String loginPageTitle = objLogin.getLoginTitle();
		Assert.assertTrue(loginPageTitle.contains("LOGIN Panel"));
	}

}

DashboardTests

import org.testng.Assert;
import org.testng.annotations.Test;

import com.example.pageobjectmodel_demo.pages.DashboardPage;
import com.example.pageobjectmodel_demo.pages.LoginPage;

public class DashboardTests extends BaseTest {

	LoginPage objLogin;
	DashboardPage objDashboardPage;

	@Test(priority = 0)
	public void DasboardTest() {

		objLogin = new LoginPage(driver);

		// login to application
		objLogin.login("Admin", "admin123");

		// go the dashboard page
		objDashboardPage = new DashboardPage(driver);

		// Verify dashboard page
		Assert.assertTrue(objDashboardPage.getHomePageText().contains("Welcome"));
	}

}

Step 8 – Create a TestNG.XML

Here, I have mentioned 2 test classes. So, when I will run the tests from TestNG.xml, it will run the tests of both the classes. If will mention any one class, then the test of that particular class will be executed.

<?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.pageobjectmodel_demo.tests.LoginTests"/>
          <class name = "com.example.pageobjectmodel_demo.tests.DashboardTests"/>
     </classes>  
   </test>
</suite>

Step 9 – 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 10 – 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.

Image of Index.html report

Image of emailable-report.html

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

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.

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 login to the 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 analyzes 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 Maven project.

Step 6 – Once I have selected the Maven project, a new dialog box will appear. IntelliJ asks you to either Trust Project or Preview 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 current window or New Window. It is always a good practice to open the project in 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 Clone a project from GitLab using Eclipse

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.

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

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 – Open Eclipse and go to File > Import in eclipse as shown in the image.

Step 3 – A window will pop up in which select Git Folder. Under Git folder, select option – Projects from Git(with smart import) as shown in the image. Click the NEXT button.

Step 4 – A new window will pop up in which select option – Clone URI as shown in the image. Click on the NEXT button.

Step 5 – Another window will pop up in which you have to paste the GitLab Repository URL and also  GitLab UserID and Password and click on the “Next” button.

URI – This is the URL that we have cloned from GitLab in Step 1.
Host – gitlab.com
Repository path – path of project in gitlab (This is auto populated after entring URI)

Autehntication
User – Username of GitLab
Password – passowrd of GitLab

Step 6 – Select master and select “When fetching a commit, also fetch its tags”. Click the “Next” button.

Step 7 –  Select the Folder directory in which you want to import the repository and click the “Finish“ button.

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 test POST Request using Rest Assured

HOME

In the last tutorial, I have explained How to test GET Request using Rest Assured. In this tutorial, I will automate a POST Request using Rest Assured. I will verify the status code, line of Status, and content of the Response. To setup a basic Rest Assured Maven Project, click here and Gradle project, click here.

What is POST Method?

An HTTP POST method is used to create a new resource in the collection of resources with a request body passed as a JSON/XML or in a different format. If a resource is created successfully by the endpoint or server, it returns a status code 201( Created) , returning a Location header with a link to the newly-created resource with the 201 HTTP status. It may return 200 (OK) and 204 (No Content) status code as well based on how API is developed.

POST is neither safe nor idempotent. It is therefore recommended for non-idempotent resource requests. Making two identical POST requests will most-likely result in two resources containing the same information.

Below are the steps to test a POST Request using Rest Assured:

Step 1 – Specify the base URL to the RESTful web service using RestAssured class.

RestAssured.baseURI = "http://dummy.restapiexample.com/api/v1/create";

Step 2 – Every Request in Rest-Assured library is represented by an interface called RequestSpecification. This interface allows to modify the request, like adding headers or adding authentication details. Use the RestAssured class to generate a RequestSpecification.

requestSpecification = RestAssured.given();

RequestSpecification is imported from package:

import io.restassured.specification.RequestSpecification;

Step 3 – Set the content type to specify format in which request payload will be send to the server. Here, the Content Type is JSON.

requestSpecification.contentType(ContentType.JSON);

contentType is imported from restassured.http package:

import io.restassured.http.ContentType;

Step 4 – Pass Request Body as String.

requestSpecification.body(jsonString);

Step 5 – Send the POST request to the server and recieve the response of the request made by REST Assured. This response contains every details returned by hitting request i.e. response body, response headers, status code, status lines, cookies etc. Response is imported from package:

import io.restassured.response.Response;

Step 6 – To validate response like status code or value , we need to get reference of type ValidatableResponseValidatableResponse is an interface. A validatable response of a request made by REST Assured. ValidatableResponse is imported from package:

import io.restassured.response.ValidatableResponse;

PrettyPrint() – It print the response body if possible and return it as string. Pretty printing is possible for content-types JSON, XML and HTML.

Below is the example of testing a POST request in Non-BDD format where I have used ValidatableResponse for the assertion of status and status line and body of the Response.

public class POST_NonBDDDemo {

	RequestSpecification requestSpecification;
	Response response;
	ValidatableResponse validatableResponse;

	@Test
	public void verifyStatusCode() {

		String jsonString = "{\"name\":\"newapitest\",\"salary\":\"4000\",\"age\":\"29\"}";

		RestAssured.baseURI = "http://dummy.restapiexample.com/api/v1/create";

		// Create a request specification
		requestSpecification = RestAssured.given();

		// Setting content type to specify format in which request payload will be sent.
		requestSpecification.contentType(ContentType.JSON);

		// Adding body as string
		requestSpecification.body(jsonString);

		// Calling POST method
		response = requestSpecification.post();

		// Let's print response body.
		String responseString = response.prettyPrint();

		/*
		 * To perform validation on response, we need to get ValidatableResponse type of
		 * response
		 */
		validatableResponse = response.then();

		// Check status code
		validatableResponse.statusCode(200);

		// It will check if status line is as expected
		validatableResponse.statusLine("HTTP/1.1 200 OK");

		// Check response body - name attribute
		validatableResponse.body("data.name", equalTo("newapitest"));

		// Check response body - message attribute
		validatableResponse.body("message", equalTo("Successfully! Record has been added."));

	}
}

The below image shows the test result of the above test.

Test implemented in BDD Format

  1. equalTo is used for assertion, is imported from a static hamcrest package:
import static org.hamcrest.Matchers.equalTo;

2. given is a static import from package:

import static io.restassured.RestAssured.given;

Below is the example of BDD Test

public class POST_BDDDemo {
	ValidatableResponse validatableResponse;

	@Test
	public void createUser() {

		String json = "{\"name\":\"apitest\",\"salary\":\"5000\",\"age\":\"30\"}";

		// GIVEN
		validatableResponse = given()
				.baseUri("http://dummy.restapiexample.com/api")
				.contentType(ContentType.JSON)
				.body(json)
				
				// WHEN
				.when()
				     .post("/v1/create")
				     
				// THEN
				.then()
				      .assertThat().statusCode(200).body("data.name", equalTo("apitest"))
				      .body("message", equalTo("Successfully! Record has been added."));
		
		System.out.println("Response :" + validatableResponse.extract().asPrettyString());
	}

}

The below image shows the test result of the above test.

The above tests can be used in both Maven and Gradle projects.

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

Rest Assured Tutorials

HOME

RestAssured is a Java-based library that is used to test RESTful Web Services. REST-assured was designed to simplify the testing and validation of REST APIs and is highly influenced by testing techniques used in dynamic languages such as Ruby and Groovy.

Chapter 1 Introduction to Rest Assured
Chapter 2 Setup Basic REST Assured Maven Project In Eclipse IDE
Chapter 3 How to test GET Request using Rest Assured
Chapter 4 How to test POST Request using Rest Assured
Chapter 5 How to test PUT Request using Rest Assured
Chapter 6 How to test DELETE Request using Rest Assured
Chapter 7 How to test POST request from JSON Object in Rest Assured
Chapter 8 How to test POST JSON Object request using Java Map in Rest Assured
Chapter 9 How to create JSON Array Request Body
Chapter 10 Assertion of JSON in Rest Assured using Hamcrest
Chapter 11 Extraction from JSON in Rest Assured
Chapter 12 How To Send A JSON/XML File As Payload To Request using Rest Assured
Chapter 13 Logging in Rest Assured

JSON Manipulation

Gradle

Chapter 1 Setup Basic REST Assured Gradle Project In Eclipse IDE

Frameworks

Chapter 1 Integration of REST Assured with TestNG
Chapter 2 Serenity BDD with Cucumber and Rest Assured
Chapter 3 Serenity BDD with Cucumber and Rest Assured in Gradle
Chapter 4 How To Create Gradle Project with Cucumber to test Rest API
Chapter 5 Rest API Test in Cucumber BDD

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 build 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 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 details, how to create a Gradle project in Eclipse, refer 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 the structure of new Gradle project.

Below is the structure and content of 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

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