2017-08-25 150 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