使用Spring Security进行JUnit测试

时间:2017-08-25 06:16:32

标签: java spring junit spring-security

我想测试,我没有被授权这样做。 这是我的代码:

/* 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

我不明白为什么这个测试不起作用。我得到了这些错误,这是我所期待的。

2 个答案:

答案 0 :(得分:1)

看起来像异常类型的问题。您期待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);
}

expected注释中删除@Test属性。 希望它有所帮助!

答案 1 :(得分:0)

您可以使用expectCause来捕捉NestedServletException

import org.junit.Rule;
import org.junit.rules.ExpectedException;

public class AuthenticationIntegrationTest {

    @Rule public ExpectedException thrown = ExpectedException.none();

    @Test
    public void postExperience() throws Exception {
        // given
        ...

        // then
        thrown.expectCause(is(instanceOf(AccessDeniedException.class)));

        // or thrown.expectCause(isA(AccessDeniedException.class));

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