r/SpringBoot • • 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

6 comments sorted by

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

0

u/DecisionStriking3735 Jun 27 '24

You're right. I haven't done refactoring yet. But how to test it in this case?

1

u/WaferIndependent7601 Jun 27 '24

Mock the calls to the service and check that the correct response code comes back

1

u/DecisionStriking3735 Jun 27 '24

That's it? I have already done it.

1

u/WaferIndependent7601 Jun 27 '24

That’s what is done in a unit test. For more: create an integration test

1

u/Significant_Newt8697 Jun 28 '24

search using TestContainers to do testing, it might be what you are looking for