2016-09-07 6 views
0

コントローラレイヤのユニットテストケースを作成しています。私はSpring SecurityContextHolderからユーザを取得しているところのコールを持っています。テストケースを実行すると、Springのセキュリティコンテキストを模倣する方法がわからないため、NULLポインタ例外が発生します。MockMVCを使用したMock SpringContextHolder

以下は私のコードです、どのようにそれを行うには?

コントローラーMethhod:

@RequestMapping(method = RequestMethod.POST) 
public void saveSettings(@RequestBody EmailSettingDTO emailSetting) { 
    User user = ((CurrentUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUser(); 
    settings.saveUserEmailSetting(user, emailSetting); 

} 

私のテストケース:

@Test public void testSaveSettings() throws Exception { 
mockMvc.perform(post(BASE_URL).content(this.objectMapper.writeValueAsString(emailDto)) 
    .contentType(MediaTypes.HAL_JSON)).andExpect(status().isOk()); 

}

+0

http://stackoverflow.com/questions/15203485/spring-test-security-how-to-mock-authenticationをご覧ください – VinayVeluri

答えて

0

この目的のために春のセキュリティテストのライブラリがあります。

これを実現するには@WithMockUserを使用できます。 post

0

あなたがUserDetailsで実行UserDetailsS​​erviceから返さエミュレートする@WithUserDetails

この注釈は、テストメソッドに追加することができます使用することができます参照してください。

は、これを使用すると、たとえば、中にテストを実行するコンテキストを作成します。

@Test 
@WithUserDetails("admin") 
public void testAdmin() throws Exception { 
    mockMvc.perform(...); 
} 

これは、管理者のSecurityContexttestAdmin()を実行します。

ただし、これを使用するにはご注意ください。 Userが名前adminで存続する必要があります。そうでないと結果の例外が発生します。

関連する問題