3

Spring 3.2.11.RELEASE と JUnit 4.11 を使用しています。特定のSpringコントローラーには、このように終了するメソッドがあります...

return new ModelAndView(new RedirectView(redirectUri, true));

JUnit テストで、送信からこの RedirectView が返されるコントローラーへの戻りを確認するにはどうすればよいですか? 以前は org.springframework.test.web.AbstractModelAndViewTests.assertViewName を使用していましたが、空でない ModelAndView オブジェクトが返された場合でも「null」しか返されません。これが私の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 が適切な値で返されることを確認する方法についてのヘルプは、感謝しています。

4

2 に答える 2

9

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

ここで一致できるものをもっと見る

于 2015-04-27T22:09:19.700 に答える