In this detailed guide, we will cover the process of creating a RESTful service using Spring Boot, Gradle, and Java. We will also demonstrate how to test the service using Postman and set up unit tests to ensure your API works as expected. This tutorial is ideal for developers aiming to build and test robust REST APIs efficiently. Let’s get started Building Testing RESTful Service with Spring Boot Gradle Postman!
Prerequisites
Before we dive in, ensure you have the following installed:
- Java Development Kit (JDK)
- Gradle
- An IDE (e.g., IntelliJ IDEA, Eclipse)
- Postman for API testing
Step 1: Setting Up the Project
1. Create a New Project Directory
Open your terminal and create a new directory for your project:
mkdir springboot-restful-service
cd springboot-restful-service
2. Initialize a Gradle Project
Initialize a new Gradle project with the following command:
gradle init --type java-application
This command sets up a basic Gradle project structure.
3. Add Spring Boot Dependencies
Open the build.gradle
file and add the necessary dependencies for Spring Boot:
plugins {
id 'org.springframework.boot' version '2.6.4'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.example'
version = '1.0.0'
sourceCompatibility = '11'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
test {
useJUnitPlatform()
}
4. Create the Main Application Class
Create the main application class at src/main/java/com/example/springbootrestfulservice/SpringbootRestfulServiceApplication.java
:
package com.example.springbootrestfulservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootRestfulServiceApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootRestfulServiceApplication.class, args);
}
}
Step 2: Creating a REST Controller
1. Create a REST Controller Class
Create a REST controller at src/main/java/com/example/springbootrestfulservice/controller/UserController.java
:
package com.example.springbootrestfulservice.controller;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/users")
public class UserController {
private List<User> users = new ArrayList<>();
@GetMapping
public List<User> getAllUsers() {
return users;
}
@GetMapping("/{id}")
public User getUserById(@PathVariable int id) {
return users.stream().filter(user -> user.getId() == id).findFirst().orElse(null);
}
@PostMapping
public User createUser(@RequestBody User user) {
users.add(user);
return user;
}
static class User {
private int id;
private String name;
private String email;
public User() {}
public User(int id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
}
Step 3: Running the Application
1. Run the Spring Boot Application
Use the following command to run your Spring Boot application:
./gradlew bootRun
Your application should now be running at http://localhost:8080
.
Step 4: Testing with Postman
1. Open Postman
Download and install Postman from Postman Download if you haven’t already.
2. Create New Requests
- GET Request:
- URL:
http://localhost:8080/users
- Click “Send” to retrieve the list of users (initially empty).
- URL:
- POST Request:
- URL:
http://localhost:8080/users
- Body: Select “raw” and “JSON” and enter the following JSON:
{ "id": 1, "name": "John Doe", "email": "john.doe@example.com" }
- URL:
- GET Request by ID:
- URL:
http://localhost:8080/users/1
- Click “Send” to retrieve the user with ID 1.
- URL:
- Click “Send” to create a new user.
Step 5: Writing Unit Tests
1. Create a Test Class
Create a test class at src/test/java/com/example/springbootrestfulservice/UserControllerTest.java
:
package com.example.springbootrestfulservice;
import com.example.springbootrestfulservice.controller.UserController;
import com.example.springbootrestfulservice.controller.UserController.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.util.Arrays;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(UserController.class)
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserController userController;
@Test
public void getAllUsersTest() throws Exception {
User user = new User(1, "John Doe", "john.doe@example.com");
given(userController.getAllUsers()).willReturn(Arrays.asList(user));
mockMvc.perform(MockMvcRequestBuilders.get("/users"))
.andExpect(status().isOk())
.andExpect(content().json("[{'id':1,'name':'John Doe','email':'john.doe@example.com'}]"));
}
@Test
public void getUserByIdTest() throws Exception {
User user = new User(1, "John Doe", "john.doe@example.com");
given(userController.getUserById(1)).willReturn(user);
mockMvc.perform(MockMvcRequestBuilders.get("/users/1"))
.andExpect(status().isOk())
.andExpect(content().json("{'id':1,'name':'John Doe','email':'john.doe@example.com'}"));
}
}
2. Run the Tests
Run your tests with the following command:
./gradlew test
Conclusion
In this blog post, we have successfully created a simple RESTful service using Spring Boot, Gradle, and Java. We set up a REST controller to handle user data, tested the service using Postman, and wrote unit tests for the controller. This step-by-step guide should help you get started with building and testing your own RESTful services.
References
By following these steps, you’ll be well on your way to creating robust and efficient RESTful services with Spring Boot and testing them effectively using Postman.