【问题标题】:Test HTTP status code of redirected URL with MockMvc使用 MockMvc 测试重定向 URL 的 HTTP 状态码
【发布时间】:2017-04-29 19:10:50
【问题描述】:

我想使用 MockMvc 在 Spring Boot 应用程序中测试登录过程。成功登录后,用户被重定向到 /home。为了测试这一点,我使用:

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

此测试提供了预期的结果。

另外,我必须测试重定向页面(/home)的HTTP状态码。假设 /home-page 返回 HTTP 500 内部服务器错误,我需要能够对此进行测试。

我尝试了以下方法:

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

如果得到 200 或 500(如果出现错误),我会得到状态码 302。

在跟随重定向 URL 时,有什么方法可以正确测试 HTTP 状态代码?

感谢和问候

【问题讨论】:

    标签: java spring-mvc spring-boot mockmvc spring-mvc-test


    【解决方案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;
    

    然后在您的测试中执行以下操作(我正在使用 mockito 的 BDD 方法):

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

    【讨论】:

      猜你喜欢
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 2019-08-26
      • 2012-01-09
      • 2019-03-28
      • 1970-01-01
      • 2017-03-06
      • 1970-01-01
      相关资源
      最近更新 更多