2017-08-25 9 views
1

私はそれを行う権限がないことをテストしたいと思います。 ここに私のコード:春のセキュリティを使ったJUnitテスト

/* imports */ 

@RunWith(SpringRunner.class) 
@SpringBootTest(classes = Application.class) 
@WebAppConfiguration 
public class AuthenticationTest { 

private UsernamePasswordAuthenticationToken authentication; 

@Autowired 
private AuthenticationManager authManager; 

    public void before() throws Exception { 
     this.authentication = new UsernamePasswordAuthenticationToken("username", "password"); 
     SecurityContextHolder.getContext().setAuthentication(manager.authenticate(authentication)); 

    } 

    @Test(expected = AccessDeniedException.class) 
    public void postExperience() throws Exception { 
     ExperienceEntity experience = new ExperienceEntity(); 
     experience.setExperience("Test"); 
     experience.setExperienceEng("Test"); 

     mockMvc.perform(
        post(URL_EXPERIENCES).principal(authentication).content(json(experience)).contentType(CONTENT_TYPE)) 
        .andExpect(status().isForbidden()); 
     } 

エラーログ:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.security.access.AccessDeniedException: Access is denied 

このテストが動作しない理由を私は理解していません。私は、私が期待したこれらのエラーを取得します。

答えて

0

例外タイプの問題のようです。あなたはAccessDeniedExceptionを期待していますが、それはNestedServletExceptionに包まれています。あなたのテストを成功させるには、あなたはそうのようにそれを行うことができます。

try { 
    mockMvc.perform(post(URL_EXPERIENCES).principal(authentication) 
     .content(json(experience)).contentType(CONTENT_TYPE)) 
     .andExpect(status().isForbidden()); 
    Assert.fail(); 
} catch (Exception e) { 
    Assert.assertTrue(e.getCause() instanceof AccessDeniedException); 
} 

そして、あなたの@Test注釈からexpectedプロパティを削除します。 お手伝い願います!

+0

ありがとうございます。できます! – Paddy3108

関連する問題