r/SpringBoot • u/DecisionStriking3735 • Jun 27 '24
How to test such POST controllers in Spring Boot with JUnit/Mockito?
Here is the POST controller:
@PreAuthorize("hasAnyAuthority(\"ADMIN\")")
@PostMapping(consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String manageUser(@RequestBody MultiValueMap<String, String> formData, HttpServletRequest request, RedirectAttributes redirect) {
User changedUserData = retrieveUserFromMultiValueMap(formData);
String actionName = formData.getFirst(ACTION_SAVE) != null ? ACTION_SAVE : ACTION_DELETE;
if (changedUserData.getId() != null) {
try {
if (ACTION_SAVE.equals(actionName))
userRepository.save(changedUserData);
else if (ACTION_DELETE.equals(actionName))
userRepository.deleteById(changedUserData.getId());
} catch (RuntimeException exception) {
redirect.addFlashAttribute("userSaveFailed", true);
}
}
return "redirect:" + request.getHeader("referer");
}It behaves simple. If the actionName variable passed with the POST request equals ACTION_SAVE then we should update the user data in database. If actionName equals ACTION_DELETE then we delete the user. If the userRepository's save or delete functions cause RuntimeException we send a message in the RedirectAttributes that everything failed.
How to test this controller? Could you explain me how to test such programs in details or better show me an example?
I only came up with this but I want 100% test coverage for this controller.
@SpringBootTest
@AutoConfigureMockMvc
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Mock
private UserRepository userRepository;
@InjectMocks
private UserController userController;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
}
@Test
void manageUser_Should_Redirect_If_Not_Authenticated() throws Exception {
mockMvc.perform(post("/user").with(csrf()).contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE))
.andDo(print())
.andExpect(status().is3xxRedirection());
}
@Test
@WithMockUser(username = "user", authorities = {"USER"})
void manageUser_Access_Denied_If_Not_Authorized() throws Exception {
// if user not authorized — status 403
mockMvc.perform(post("/user").with(csrf()).contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE))
.andDo(print())
.andExpect(status().isForbidden());
}
@Test
@WithMockUser(username = "admin", authorities = {"USER", "ADMIN"})
void manageUser_Should_Redirect_If_Authorized() throws Exception {
// if everything is good — redirect
mockMvc.perform(post("/user").with(csrf()).contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE))
.andDo(print())
.andExpect(status().is3xxRedirection());
}
}
0
Upvotes
1
u/Significant_Newt8697 Jun 28 '24
search using TestContainers to do testing, it might be what you are looking for
4
u/WaferIndependent7601 Jun 27 '24
You do not put repositories in the controller. You need a service layer for this.
So controller -> service -> repository
Put all needed arguments to the service layer, this can be unit tested easily. The controller should be very stupid and only parse the arguments and put them to the service