Introduction:
Spring Boot is a popular Java framework used to build robust and scalable applications. While it provides an easy way to build applications, it is equally important to ensure that they are thoroughly tested before deployment.
In this blog post, we will explore how to test Spring Boot applications using two popular testing frameworks - JUnit and Mockito.
Here's an example of testing a Spring Boot controller with JUnit and Mockito:
Assume that we have a simple Spring Boot application with a UserController that handles CRUD operations on user entities. We want to test the UserController to ensure that it behaves correctly.
UserController:
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
User user = userService.getUserById(id);
if (user != null) {
return ResponseEntity.ok(user);
} else {
return ResponseEntity.notFound().build();
}
}
@PostMapping
public ResponseEntity<User> createUser(@RequestBody User user) {
User createdUser = userService.createUser(user);
return ResponseEntity.created(URI.create("/users/" + createdUser.getId())).body(createdUser);
}
// ... other CRUD operations
}
We want to test the getUserById() method to ensure that it returns the correct response for both existing and non-existing users.
UserControllerTest:
@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserService userService;
@Test
public void testGetUserById() throws Exception {
// Setup
User user = new User(1L, "John", "Doe");
Mockito.when(userService.getUserById(1L)).thenReturn(user);
// Execute and Assert
mockMvc.perform(MockMvcRequestBuilders.get("/users/1"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(user.getId()))
.andExpect(MockMvcResultMatchers.jsonPath("$.firstName").value(user.getFirstName()))
.andExpect(MockMvcResultMatchers.jsonPath("$.lastName").value(user.getLastName()));
// Setup
Mockito.when(userService.getUserById(2L)).thenReturn(null);
// Execute and Assert
mockMvc.perform(MockMvcRequestBuilders.get("/users/2"))
.andExpect(MockMvcResultMatchers.status().isNotFound());
}
// ... other test methods
}
This is just a simple example, but it demonstrates how to use JUnit and Mockito to test Spring Boot components. By writing more comprehensive tests like this, you can ensure that your Spring Boot application is reliable and performs as expected.
Need help in your spring boot project work??
For any Spring boot project assistance or job support connect with Codersarts. At Codersarts you get project help and job support revolving around technologies like Java, Spring Boot, Angular, React, ML and so on. Take me to codersarts
Commenti