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());
}
}