The Wayback Machine - https://web.archive.org/web/20240927193609/https://www.geeksforgeeks.org/how-to-test-spring-boot-project-using-zerocode/
Open In App

How to Test Spring Boot Project using ZeroCode?

Last Updated : 15 Nov, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Zerocode automated testing framework for a REST API project concept is getting seen via this tutorial by taking a sample spring boot maven project. Let us see the dependencies for Zerocode :

<dependency>
      <groupId>org.jsmart</groupId>
      <artifactId>zerocode-tdd</artifactId>
      <version>1.3.27</version>
      <scope>test</scope>
 </dependency>

Zerocode framework supports the following

  • REST
  • SOAP
  • Security
  • Load/Stress
  • Database
  • Apache Kafka
  • GraphQL

In this tutorial let us see REST API testing.

Example Project

Project Structure:

Project Structure

 

pom.xml

XML




<?xml version="1.0" encoding="UTF-8"?>
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
                        http://maven.apache.org/xsd/maven-4.0.0.xsd">
    
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.gfg.zerocode</groupId>
    <artifactId>zerocode</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>${spring.boot.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>${spring.boot.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.jsmart</groupId>
            <artifactId>zerocode-tdd</artifactId>
            <version>${zerocode-tdd.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
  
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <profiles>
                        <profile>it</profile>
                    </profiles>
                </configuration>
                <executions>
                    <execution>
                        <id>pre-integration-test</id>
                        <goals>
                            <goal>start</goal>
                        </goals>
                        <configuration>
                            <skip>${skip.it}</skip>
                        </configuration>
                    </execution>
                    <execution>
                        <id>post-integration-test</id>
                        <goals>
                            <goal>stop</goal>
                        </goals>
                        <configuration>
                            <skip>${skip.it}</skip>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>${maven-failsafe-plugin.version}</version>
                <configuration>
                    <skip>${skip.it}</skip>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.apache.maven.surefire</groupId>
                        <artifactId>surefire-junit47</artifactId>
                        <version>${surefire-junit47.version}</version>
                    </dependency>
                </dependencies>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
  
    <properties>
        <maven-failsafe-plugin.version>3.0.0-M5</maven-failsafe-plugin.version>
        <surefire-junit47.version>3.0.0-M5</surefire-junit47.version>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <spring.boot.version>2.4.2</spring.boot.version>
        <skip.it>true</skip.it>
        <zerocode-tdd.version>1.3.27</zerocode-tdd.version>
    </properties>
  
</project>


To test REST API, let us create a sample spring boot application. Let us create the model class first

GeekUser.java

Java




public class GeekUser {
    
    private String id;
    private String firstName;
    private String lastName;
    private String departmentName;
    
    public String getDepartmentName() {
        return departmentName;
    }
  
    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }
  
    public float getSalary() {
        return salary;
    }
  
    public void setSalary(float salary) {
        this.salary = salary;
    }
  
    private float salary;
  
    public String getId() {
        return id;
    }
  
    public void setId(String id) {
        this.id = id;
    }
  
    public String getFirstName() {
        return firstName;
    }
  
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
  
    public String getLastName() {
        return lastName;
    }
  
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}


GeekUserZerocodeApplication.java

Java




import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
  
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
  
@SpringBootApplication
@RestController
@RequestMapping("/api/users")
public class GeekUserZerocodeApplication {
    private List<GeekUser> users = new ArrayList<>();
  
    public static void main(String[] args) {
        SpringApplication.run(GeekUserZerocodeApplication.class, args);
    }
  
    @PostMapping
    public ResponseEntity create(@RequestBody GeekUser user) {
        if (!StringUtils.hasText(user.getFirstName())) {
            return new ResponseEntity("firstName can't be empty!", HttpStatus.BAD_REQUEST);
        }
        if (!StringUtils.hasText(user.getLastName())) {
            return new ResponseEntity("lastName can't be empty!", HttpStatus.BAD_REQUEST);
        }
        if (!StringUtils.hasText(user.getDepartmentName())) {
            return new ResponseEntity("DeparmentName can't be empty!", HttpStatus.BAD_REQUEST);
        }
        if (user.getSalary() < 0 ) {
            return new ResponseEntity("Salary is not valid!", HttpStatus.BAD_REQUEST);
        }
        user.setId(UUID.randomUUID()
            .toString());
        users.add(user);
        return new ResponseEntity(user, HttpStatus.CREATED);
    }
  
}


We have to write a scenario to test the same

{
  "scenarioName": "geek test user creation endpoint",
  "steps": [  // Array of JSON objects, as much we want we can store
    {
      "name": "geek_test_successful_creation",
      "url": "/api/users", // Relative URL
      "method": "POST",
      "request": {
        "body": { // We have to specify whole bean class parameter and its values
          "firstName": "Rachel",
          "lastName": "Green",
          "departmentName":"IT",
          "salary":100000.0
        }
      },
      "verify": { // expected part containing status and body
        "status": 201, // status code for a given HTTP call
        "body": { // Resultant body from the call
          "id": "$NOT.NULL",
          "firstName": "Rachel",
          "lastName": "Green",
          "departmentName":"IT",
          "salary":100000.0
        }
      }
    }
}

The above one is a success call that creates a user. Similarly, we can do for validation part as well

 {
      "name": "test_firstname_validation",
      "url": "/api/users",
      "method": "POST",
      "request": {
        "body": {
          "firstName": "",
          "lastName": "Bing",
          "departmentName":"IT",
          "salary":100000.0
        }
      },
      "assertions": {
        "status": 400,
        "rawBody": "firstName can't be empty!"
      }
    },
    {
      "name": "test_lastname_validation",
      "url": "/api/users",
      "method": "POST",
      "request": {
        "body": {
          "firstName": "Monica",
          "lastName": "",
          "departmentName":"Chef",
          "salary":100000.0
        }
      },
      "assertions": {
        "status": 400,
        "rawBody": "lastName can't be empty!"
      }
    },
   {
      "name": "test_departmentname_validation",
      "url": "/api/users",
      "method": "POST",
      "request": {
        "body": {
          "firstName": "Phoebe",
          "lastName": "Buffe",
          "departmentName":"",
          "salary":50000.0
        }
      },
      "assertions": {
        "status": 400,
        "rawBody": "DeparmentName can't be empty!"
      }
    }

We can combine everything together and keep it under the test/resources folder. Basically, it is a JSON file and combines all the entries that are getting tested. Now coming to the test file part

  • @RunWith(ZeroCodeUnitRunner.class) – ZeroCodeUnitRunner, as it is responsible for it
  • @TargetEnv – Provide the property file that is required for running the scenario

GeekUserEndpointIT.java

Java




import org.jsmart.zerocode.core.domain.Scenario;
import org.jsmart.zerocode.core.domain.TargetEnv;
import org.jsmart.zerocode.core.runner.ZeroCodeUnitRunner;
import org.junit.Test;
import org.junit.runner.RunWith;
  
// Here in RunWith it has been specified
// as ZeroCodeUnitRunner, as it is responsible
@RunWith(ZeroCodeUnitRunner.class)
// @TargetEnv – this points to the property file 
// that will be used when our scenario runs
@TargetEnv("rest_api.properties")
public class GeekUserEndpointIT {
  
    @Test
    @Scenario("rest/geek_user_create_test.json")
    public void test_geekuser_creation_endpoint() {
    }
  
}


rest_api.properties

web.application.endpoint.host=http://localhost # In case of changes they need to be modified appropriately
web.application.endpoint.port=8080
web.application.endpoint.context=

For the execution of tests, in pom.xml necessary dependencies are added

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-failsafe-plugin</artifactId>
    <version>3.0.0-M5</version>
    <dependencies>
        <dependency>
            <groupId>org.apache.maven.surefire</groupId>
            <artifactId>surefire-junit47</artifactId>
            <version>3.0.0-M5</version>
        </dependency>
    </dependencies>
    <executions>
        <execution>
            <goals>
                <goal>integration-test</goal>
                <goal>verify</goal>
            </goals>
        </execution>
    </executions>
</plugin>

We can run the project in the command line by using

mvn verify -Dskip.it=false

Under the target folder of the directory, we can see multiple files that help to understand different layers of testing

 

Similarly whatever testing scenarios given are validated against Zerocode

 



Previous Article
Next Article

Similar Reads

Spring Boot – Setting Up a Spring Boot Project with Gradle
Spring Boot is a Java framework designed to simplify the development of stand-alone, production-ready Spring applications with minimal setup and configuration. It simplifies the setup and development of new Spring applications, reducing boilerplate code. In this article, we will guide you through setting up a Spring Boot project using Gradle, a wid
4 min read
Spring Boot – Using Spring Boot with Apache Camel
Apache Camel and Spring Boot are two powerful frameworks that can be seamlessly integrated to build robust, scalable, and efficient applications. Apache Camel is an open-source integration framework that provides an extensive range of components and connectors, enabling developers to integrate different systems, APIs, and applications. It simplifie
5 min read
Difference Between Spring Boot Starter Web and Spring Boot Starter Tomcat
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
3 min read
Spring Boot – Handling Background Tasks with Spring Boot
Efficiently handling background tasks with Spring Boot is important for providing a smooth user experience and optimizing resource utilization. Background tasks refer to operations that are performed asynchronously or in the background, allowing the main application to continue processing other requests. In a Spring Boot application, background tas
5 min read
Migrate Application From Spring Boot 2 to Spring Boot 3
With the release of Spring Boot 3, significant changes and improvements have been introduced, particularly around Jakarta EE compliance, Java 17 support, and GraalVM native images. If you are using Spring Boot 2 and are considering migrating to Spring Boot 3, this article will walk you through the necessary steps, considerations, and potential pitf
5 min read
Spring Boot - Customizing Spring Boot Starter
Spring Boot Starters are specialized project types designed to encapsulate and distribute common functionality, simplifying the setup of Spring Boot applications. Official starters, like spring-boot-starter-web and spring-boot-starter-data-jpa, bundle dependencies, configurations, and pre-built beans for specific use cases. Creating a custom Spring
6 min read
How to Make a Project Using Spring Boot, MySQL, Spring Data JPA, and Maven?
For the sample project, below mentioned tools got used Java 8Eclipse IDE for developmentHibernate ORM, Spring framework with Spring Data JPAMySQL database, MySQL Connector Java as JDBC driver.Example Project Using Spring Boot, MySQL, Spring Data JPA, and Maven Project Structure: As this is getting prepared as a maven project, all dependencies are s
4 min read
Spring Boot - Spring JDBC vs Spring Data JDBC
Spring JDBC Spring can perform JDBC operations by having connectivity with any one of jars of RDBMS like MySQL, Oracle, or SQL Server, etc., For example, if we are connecting with MySQL, then we need to connect "mysql-connector-java". Let us see how a pom.xml file of a maven project looks like. C/C++ Code <?xml version="1.0" encoding=
4 min read
Spring vs Spring Boot vs Spring MVC
Are you ready to dive into the exciting world of Java development? Whether you're a seasoned pro or just starting out, this article is your gateway to mastering the top frameworks and technologies in Java development. We'll explore the Spring framework, known for its versatility and lightweight nature, making it perfect for enterprise-level softwar
8 min read
How to Create a Spring Boot Project in Spring Initializr and Run it in IntelliJ IDEA?
Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using Java is that it tries to connect every concept in the language to the real world with the help
3 min read
How to Create and Setup Spring Boot Project in Spring Tool Suite?
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
3 min read
Java Spring Boot Microservices - Develop API Gateway Using Spring Cloud Gateway
The API Gateway Pattern in some cases stands for “Backend for frontend”. It is basically the entry gate for taking entry into any application by an external source. The pattern is going on in a programmer’s mind while they are making the client’s application. It acts as a medium between the client applications and microservices. For example-Netflix
4 min read
Spring Boot | How to access database using Spring Data JPA
Spring Data JPA is a method to implement JPA repositories to add the data access layer in applications easily. CRUD stands for create, retrieve, update, delete which are the possible operations which can be performed in a database. In this article, we will see an example of how to access data from a database(MySQL for this article) in a spring boot
4 min read
Spring Boot - Reactive Programming Using Spring Webflux Framework
In this article, we will explore React programming in Spring Boot, Reactive programming is an asynchronous, non-blocking programming paradigm for developing highly responsive applications that react to external stimuli. What is Reactive ProgrammingIn reactive programming, the flow of data is asynchronous through push-based publishers and subscriber
4 min read
Spring Boot Batch Processing Using Spring Data JPA to CSV File
The Spring Batch is a framework in the Spring Boot ecosystem It can provide a lot of functionalities for Batch processing. The Spring Batch framework simplifies the batch development of applications by providing reliable components and other patterns for common batch processing concerns. Mostly, batch processing is used to read and write data in bu
7 min read
Spring Boot 3.0 - JWT Authentication with Spring Security using MySQL Database
In Spring Security 5.7.0, the spring team deprecated the WebSecurityConfigurerAdapter, as they encourage users to move towards a component-based security configuration. Spring Boot 3.0 has come with many changes in Spring Security . In this article, we'll learn how to implement JWT authentication and authorization in a Spring Boot 3.0 application u
9 min read
Spring Boot - Project Deployment Using Tomcat
Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because it’s a rapid production-ready environment that enables the developers to directly foc
5 min read
Creating Spring Boot Project Using STS
Spring Boot is one of the favorite items of Spring Framework, as it requires very minimal configuration, unlike Spring MVC. Spring Boot applications are easily configurable and have several other benefits to use for developing stand-alone Java applications. Spring Boot comes with, Embedded Tomcat'Starter' dependency for easy configurationAutomatica
4 min read
How to encrypt passwords in a Spring Boot project using Jasypt
In this article, we will learn how to encrypt data in Spring Boot application config files like application.properties or application.yml. Inside those files, we can encrypt username, password, etc. You often come across developing projects where you have to connect to databases like MongoDB, etc, and store the authentic password of the DB connecti
4 min read
Generate Model Classes using jsonSchema2Pojo (website and Maven Dependency) For a Spring Boot Project That Consumes API
Generating Java model classes from a JSON schema is a common task when building applications that consume APIs, especially in Spring Boot projects. It simplifies the development process by mapping POJOs (Plain Old Java Objects) directly to the API's JSON structure. In this article, we explore how to use jsonSchema2Pojo, both as a web tool and as a
4 min read
Employee Management System Project using Spring Boot
The Employee Management System includes operations like adding new Employees into the Database, updating existing Employees, Delete Employees, Retrieving All Employees' Data in the form of a Table and the final one is Delete All Employees. In This Article, we will learn about Employee Management systems such as EMS App or EMS. Mostly This Spring bo
15+ min read
Unit Testing in Spring Boot Project using Mockito and Junit
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
6 min read
How to Run Your First Spring Boot Application in Spring Tool Suite?
Spring Tool Suite (STS) is a java IDE tailored for developing Spring-based enterprise applications. It is easier, faster, and more convenient. And most importantly it is based on Eclipse IDE. STS is free, open-source, and powered by VMware. Spring Tools 4 is the next generation of Spring tooling for the favorite coding environment. Largely rebuilt
3 min read
Java Spring Boot Microservices – Integration of Eureka and Spring Cloud Gateway
Microservices are small, loosely coupled distributed services. Microservices architecture evolved as a solution to the scalability, independently deployable, and innovation challenges with Monolithic Architecture. It provides us to take a big application and break it into efficiently manageable small components with some specified responsibilities.
5 min read
What's New in Spring 6 and Spring Boot 3?
Spring and Spring Boot are two of the most popular Java frameworks used by developers worldwide. The Spring team is continuously working on improving and enhancing the frameworks with each new major release. Spring 6 and Spring Boot 3 are expected to bring in significant new features and changes that will further boost development with these techno
5 min read
How to Integrate Keycloak with Spring Boot and Spring Security?
Keycloak is Open Source Identity and Access Management (IAM) solution developed by Red Hat. By using this you can add authentication to applications and secure services with minimum effort. No need to deal with storing users or authenticating users. Keycloak provides user federation, strong authentication, user management, fine-grained authorizatio
2 min read
Java Spring Boot Microservices - Integration of Eureka, Feign & Spring Cloud Load Balancer
Microservices are small, loosely coupled distributed services. Microservices architecture evolved as a solution to the scalability, independently deployable, and innovation challenges with Monolithic Architecture. It provides us to take a big application and break it into efficiently manageable small components with some specified responsibilities.
13 min read
Java Spring Boot Microservices - Client Side Load Balancing with Spring Cloud LoadBalancer
Spring Cloud is a collection of projects like load balancing, service discovery, circuit breakers, routing, micro-proxy, etc will be given by Spring Cloud. So spring Cloud basically provides some of the common tools and techniques and projects to quickly develop some common patterns of the microservices. Basically, there are two ways to load balanc
12 min read
Spring Cloud Vs Spring Boot Actuator
Spring CloudSpring Cloud's main purpose is to give tools and services for managing and making distributed systems, especially in a microservices architecture. The developer wants to speed up the process of building patterns in distributed systems, these tools can fulfill their requirement. They include almost all from the management of configuratio
5 min read
Configuring Multiple Spring Batch Jobs in a Spring Boot Application
Spring Batch serves as a robust framework within the Spring ecosystem, specifically tailored for managing batch processing tasks efficiently. It's designed to tackle big data jobs efficiently and comes with handy tools to make batch application development a breeze. In the context of a Spring Boot application, setting up multiple Spring Batch jobs
10 min read