Spring Boot Backend Development Course, Spring Boot 3 and Testing

In modern software development, rapid deployment and flexibility are very important. To meet these requirements, Spring Boot has gained popularity among many developers. In this article, we will take a detailed look at the main features of Spring Boot 3 and effective testing methods.

1. Understanding Spring Boot

Spring Boot is a development tool based on the Spring Framework, designed to make it easier to set up and run Spring applications. By using Spring Boot, you can avoid complex XML configurations and set up your application with simple annotations.

1.1 Features of Spring Boot

  • Automatic Configuration: Spring Boot automatically configures the necessary settings, reducing development time.
  • Standalone: Spring Boot projects are packaged as standalone JAR files, making them easy to deploy.
  • Simplified Configuration: Reduces complex XML configurations and allows for simple setups using annotations.
  • Simple Customization: Allows for easy customization of application behavior through various properties.

2. New Features of Spring Boot 3

Spring Boot 3 has introduced several new features and improvements compared to previous versions. In this section, we will look at the main features.

2.1 Support for Java 17

Spring Boot 3 natively supports Java 17. It allows you to leverage the new features and improvements of Java 17 to write safer and more efficient code.

2.2 New Dependency Management

Spring Boot 3 provides a new mechanism to manage various dependencies more easily, helping developers select libraries and adjust versions as needed.

2.3 Improved Performance

Spring Boot 3 has optimized its internal engine to improve application kill chain performance. As a result, you can expect faster boot times and better response speeds.

3. Developing Backend with Spring Boot 3

Now, let’s take a look at the process of creating a simple CRUD (Create, Read, Update, Delete) application using Spring Boot. We will proceed step by step.

3.1 Project Setup

Let’s configure the necessary settings to start a Spring Boot application. First, we will create a new project using Spring Initializr. Select required dependencies such as ‘Spring Web’, ‘Spring Data JPA’, and ‘H2 Database’.

3.2 Application Structure

The structure of the generated project is as follows.

src
└── main
    ├── java
    │   └── com
    │       └── example
    │           └── demo
    │               ├── DemoApplication.java
    │               ├── controller
    │               ├── model
    │               └── repository
    └── resources
        └── application.properties

3.3 Creating Model Class

First, we will create an entity class to be stored in the database. For example, let’s create a model class called ‘User’.

package com.example.demo.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String email;

    // Getters and setters
}

3.4 Creating Repository Interface

We will create a repository interface to interact with the database using Spring Data JPA.

package com.example.demo.repository;

import com.example.demo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository {
}

3.5 Creating Controller Class

We will write a controller class to provide RESTful APIs.

package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping
    public List getAllUsers() {
        return userRepository.findAll();
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        return userRepository.save(user);
    }
    
    // Add methods for updating and deleting users
}

3.6 Running the Application

Once all configurations are complete, please run the application. You can use the command ./mvnw spring-boot:run to execute it.

4. Spring Boot Testing

Testing is very important during the application development process. Spring Boot provides various tools and frameworks for testing.

4.1 Types of Testing in Spring Boot

Spring Boot supports several types of testing:

  • Unit Test: Validates the behavior of individual methods or classes.
  • Integration Test: Validates whether multiple components work together.
  • End-to-End Test: Validates that the entire functionality of the application works correctly.

4.2 Writing Unit Tests

Let’s write a simple unit test. We will test the UserService class using JUnit 5 and Mockito.

package com.example.demo.service;

import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import static org.mockito.Mockito.when;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class UserServiceTest {

    @InjectMocks
    private UserService userService;

    @Mock
    private UserRepository userRepository;

    public UserServiceTest() {
        MockitoAnnotations.openMocks(this);
    }

    @Test
    void testCreateUser() {
        User user = new User();
        user.setName("John Doe");
        user.setEmail("john@example.com");

        when(userRepository.save(user)).thenReturn(user);

        User createdUser = userService.createUser(user);
        assertEquals("John Doe", createdUser.getName());
    }
}

4.3 Writing Integration Tests

Let’s also look at how to perform integration testing in Spring Boot. We can use the @SpringBootTest annotation for this.

package com.example.demo;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testCreateUser() throws Exception {
        String json = "{\"name\":\"John Doe\", \"email\":\"john@example.com\"}";

        mockMvc.perform(post("/api/users")
                .contentType("application/json")
                .content(json))
                .andExpect(status().isCreated());
    }
}

5. Conclusion

In this opportunity, we learned about the key features and testing methods of Spring Boot 3. Spring Boot is a powerful tool that helps developers quickly build and reliably operate applications. It is important to effectively develop backend systems using various features and improve the quality of applications through testing.

We hope you continue to gain experience by working on more projects using Spring Boot and grow into a better developer.