Dav*_*ave 3 junit spring modelandview
我正在使用Spring 3.2.11.RELEASE和JUnit 4.11.在一个特定的Spring控制器中,我有一个方法,因此结束......
return new ModelAndView(new RedirectView(redirectUri, true));
Run Code Online (Sandbox Code Playgroud)
在我的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");
Run Code Online (Sandbox Code Playgroud)
有关如何验证RedirectView是否返回正确值的任何帮助都是值得赞赏的,
正如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();
}
}
Run Code Online (Sandbox Code Playgroud)
然后你只需要使用MockMvcResultMatchers来断言
@Test
public void testMyRedirect() throws Exception {
mockMvc.perform(post("you/url/")
.andExpect(status().isOk())
.andExpect(redirectUrl("you/redirect")
}
Run Code Online (Sandbox Code Playgroud)
注意:post(), status() isOk() redirectUrl()是从静态导入MockMvcResultMatchers
在这里查看更多您可以匹配的内容
| 归档时间: |
|
| 查看次数: |
5743 次 |
| 最近记录: |