Check redirect URL HTTP status code using MockMvc

I want to test the login process of a Spring boot application using MockMvc. After successful login, the user is redirected to / home. To test this, I use:

@Test
public void testLogin() throws Exception {
    RequestBuilder requestBuilder = formLogin().user("test@tester.de").password("test");
    mockMvc.perform(requestBuilder).andExpect(redirectedUrl("/home")).andExpect(status().isFound());
}

This test provides the expected results.

In addition, I have to check the HTTP status code of the redirected page (/ home). Assuming the / home page returns an internal HTTP 500 server error, I need to check this.

I tried the following:

@Test
public void testLogin() throws Exception {
    RequestBuilder requestBuilder = formLogin().user("test@tester.de").password("test");
    mockMvc.perform(requestBuilder).andExpect(redirectedUrl("/home")).andExpect(status().isFound());
    mockMvc.perform(get("/home").with(csrf())).andExpect(status().isOk());
}

Instead, if you get 200 or 500 (in case of an error), I get a status code of 302.

Is there a way to correctly check the HTTP status code when using a redirect URL?

Thanks and best regards

+4
1

-, 2 , 2 :

@Test
public void testSuccessfulLogin() throws Exception {
    RequestBuilder requestBuilder = formLogin().user("test@tester.de").password("test");
    mockMvc.perform(requestBuilder).andExpect(redirectedUrl("/home")).andExpect(status().isFound());
}

@Test
public void testHomepageThrows500() throws Exception {

    // configure a mock service in the controller to throw an exception

    RequestBuilder requestBuilder = formLogin().user("test@tester.de").password("test");
    mockMvc.perform(requestBuilder).andExpect(redirectedUrl("/home")).andExpect(status().is5xxServerError());
}

- .

, , , ( ) HTTP 500.
, - , , .
HTTP 500, . , , - , . , .

:

@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(HomeController.class)
public class HomeControllerIntegrationTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private YourService yourService;

- ( BDD mockito):

@Test
public void testHomepageThrows500() throws Exception {

    given(yourService.someMethod()).willThrow(new Exception("something bad happened");

    RequestBuilder requestBuilder = formLogin().user("test@tester.de").password("test");
    mockMvc.perform(requestBuilder).andExpect(redirectedUrl("/home")).andExpect(status().is5xxServerError());
}
+3

Source: https://habr.com/ru/post/1663746/


All Articles