我使用Spring 3.2.11.RELEASE和JUnit 4.11。在一个特定的Spring控制器中,我有一个方法结束......
return new ModelAndView(new RedirectView(redirectUri, true));
在我的JUnit测试中,如何验证从提交到我的控制器的返回,其中返回了此RedirectView?我以前使用org.springframework.test.web.AbstractModelAndViewTests.assertViewName,但只返回" null",即使返回非空的ModelAndView对象也是如此。以下是我构建JUnit测试的方法......
request.setRequestURI(“/mypage/launch");
request.setMethod("POST");
…
final Object handler = handlerMapping.getHandler(request).getHandler();
final ModelAndView mav = handlerAdapter.handle(request, response, handler);
assertViewName(mav, "redirect:/landing");
有关如何验证RedirectView是否返回正确值的任何帮助都是值得赞赏的,
答案 0 :(得分:8)
正如Koiter所说,考虑转向弹簧测试a和MockMvc
它提供了一些以声明方式测试控制器和请求/响应的方法
您需要@Autowired WebApplicationContext wac;
并在@Before
方法设置中使用此类@WebAppConfiguration
。
你最终会得到一些东西
@ContextConfiguration("youconfighere.xml")
//or (classes = {YourClassConfig.class}
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class MyControllerTests {
@Autowired WebApplicationContext wac
private MockMvc mockMvc;
@Before
public void setup() {
//setup the mock to use the web context
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
}
然后你只需要使用MockMvcResultMatchers来断言
@Test
public void testMyRedirect() throws Exception {
mockMvc.perform(post("you/url/")
.andExpect(status().isOk())
.andExpect(redirectUrl("you/redirect")
}
注意:post(), status() isOk() redirectUrl()
是来自MockMvcResultMatchers
查看更多您可以匹配的内容here
答案 1 :(得分:0)
考虑将您的工具更改为MockMvc。
首先,你应该根据你的控制器创建你的MockMvc。
private MockMvc mockController;
mockController =
MockMvcBuilders.standaloneSetup(loginController).setCustomArgumentResolvers(
new ServletWebArgumentResolverAdapter(new PageableArgumentResolver())).build();
创建该对象后,使用请求信息构建请求。部分内容是API中包含的断言选项。
mockController.perform(MockMvcRequestBuilders.get(LoginControllerTest.LOGIN_CONTROLLER_URL + "?logout=true").
principal(SessionProvider.getPrincipal("GonLu004")))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.view().name("jsp/login"))
.andExpect(MockMvcResultMatchers.model().attribute("logOutMessage", logoutMessage));
MockMvcResultMatchers包含审核重定向information的方法。
来自spring的MockMvc是在控制器层上应用单元测试的不错选择。