使用Spring Security测试Spring Data JPA存储库的单元

时间:2015-05-13 02:26:50

标签: spring security unit-testing jpa repository

我有一个Spring Data JPA存储库,并且单元测试工作正常,只要未添加Spring Security依赖项(spring-boot-starter-security),并在存储库上使用相应的方法授权注释。添加后,我在运行单元测试时会收到AuthenticationCredentialsNotFound异常。

如何在单元测试中“验证”对存储库方法的调用?

2 个答案:

答案 0 :(得分:2)

我找到了一个如何做的例子: https://github.com/spring-projects/spring-data-examples/blob/master/jpa/security/src/test/java/example/springdata/jpa/security/SecurityIntegrationTests.java

我的测试现在运行正常,只要在调用存储库上的方法之前,我首先验证具有所需角色的用户:

SecurityContextHolder.getContext()
    .setAuthentication(new UsernamePasswordAuthenticationToken(
        "admin",
        "password",
        Collections.singleton(new SimpleGrantedAuthority("ROLE_ADMIN"))));

// Make calls to repository methods that require the admin role

答案 1 :(得分:2)

如果您需要验证设置多个角色(由Rob Winch提供 - Spring Security Lead):

SecurityContextHolder.getContext()
    .setAuthentication(new UsernamePasswordAuthenticationToken(
        ADMIN,
        PASSWORD,   
        AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN")
));