使用Spring安全性对Spring数据JPA存储库进行单元测试

使用Spring安全性对Spring数据JPA存储库进行单元测试,spring,security,unit-testing,jpa,repository,Spring,Security,Unit Testing,Jpa,Repository,我有一个SpringDataJPA存储库,只要不添加SpringSecurity依赖项(SpringBootStarter安全性)以及存储库中相应的方法授权注释,单元测试就可以正常工作。添加后,我在运行单元测试时会出现AuthenticationCredentialsNotFound异常 如何在单元测试中“验证”对存储库方法的调用?我在这里找到了一个示例: 我的测试现在运行良好,只要在调用存储库中的方法之前,我首先对具有所需角色的用户进行身份验证,如下所示: SecurityContextHo

我有一个SpringDataJPA存储库,只要不添加SpringSecurity依赖项(SpringBootStarter安全性)以及存储库中相应的方法授权注释,单元测试就可以正常工作。添加后,我在运行单元测试时会出现AuthenticationCredentialsNotFound异常


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

我在这里找到了一个示例:

我的测试现在运行良好,只要在调用存储库中的方法之前,我首先对具有所需角色的用户进行身份验证,如下所示:

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

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

我在这里找到了一个示例:

我的测试现在运行良好,只要在调用存储库中的方法之前,我首先对具有所需角色的用户进行身份验证,如下所示:

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

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

此外,如果您需要验证,请设置多个角色(Rob Winch-Spring安全负责人提供):


此外,如果您需要验证,请设置多个角色(Rob Winch-Spring安全负责人提供):


您使用什么身份验证?OAuth2?现在我只使用基本的身份验证,我有带有
@PreAuthorize
注释的存储库方法。您使用什么身份验证?OAuth2?现在我只使用基本的身份验证,我用
@PreAuthorize
注释注释了存储库方法。