jav spring boot mastery

Testing in Spring Boot (Unit + Integration) [Java Spring Boot Mastery Series – Part 12]

Testing ensures the reliability and maintainability of your codebase.

✅ 1. Unit Testing with JUnit and Mockito

Dependency (Maven)

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

Sample Unit Test (Service Layer)

@SpringBootTest
public class UserServiceTest {

    @MockBean
    private UserRepository userRepository;

    @Autowired
    private UserService userService;

    @Test
    public void testGetUserById() {
        User mockUser = new User(1L, "Alice", "[email protected]");
        Mockito.when(userRepository.findById(1L)).thenReturn(Optional.of(mockUser));

        User user = userService.getUserById(1L);
        assertEquals("Alice", user.getName());
    }
}

Explanation:

  • @MockBean is used to mock dependencies.
  • @SpringBootTest loads context.
  • Use Mockito.when to simulate data returns

🔄 2. Integration Testing with TestRestTemplate

Sample Test

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserControllerIntegrationTest {

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void testGetUser() {
        ResponseEntity<User> response = restTemplate.getForEntity("/api/users/1", User.class);
        assertEquals(HttpStatus.OK, response.getStatusCode());
        assertNotNull(response.getBody());
    }
}

Explanation:

  • Uses a real Spring Boot context and in-memory server.
  • TestRestTemplate is used to simulate REST calls.

🧹 3. Best Practices for Testing

  • Separate unit vs. integration tests using naming or packages.
  • Use @DataJpaTest for repository testing.
  • Use @WebMvcTest for controller-only tests.
  • Keep tests independent and stateless.

➡️ Next Up: Part 13 – Spring Boot with Docker & Deployment

Similar Posts