我想使用 MockMvc 在 Spring Boot 应用程序中测试登录过程。成功登录后,用户将被重定向到/home。为了测试这一点,我使用:
@Test
public void testLogin() throws Exception {
RequestBuilder requestBuilder = formLogin().user("[email protected] /cdn-cgi/l/email-protection").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("[email protected] /cdn-cgi/l/email-protection").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 状态代码?
谢谢并致以诚挚的问候
首先,我会将您的测试分为 2 个单独的测试,因为您正在测试 2 个完全不同的场景:
@Test
public void testSuccessfulLogin() throws Exception {
RequestBuilder requestBuilder = formLogin().user("[email protected] /cdn-cgi/l/email-protection").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("[email protected] /cdn-cgi/l/email-protection").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("[email protected] /cdn-cgi/l/email-protection").password("test");
mockMvc.perform(requestBuilder).andExpect(redirectedUrl("/home")).andExpect(status().is5xxServerError());
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)