我想测试一下,我是否无权这样做。 这是我的代码:
/* 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
我不明白为什么这个测试不起作用。我收到这些错误,这是我所预料的。
最佳答案
看起来像是异常类型的问题。您期待 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
属性。
希望对您有帮助!
关于java - 使用 Spring Security 进行 JUnit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45875424/