是否可以仅将 spring 安全配置加载到我使用 junit 5 的测试中?

Is it possible to only load spring security config to my test with junit 5?

我想在检查我找到的文档时使用基于方法的安全性对我的控制器安全性进行单元测试 this 但它使用 @RunWith 并且它似乎不是仅加载安全配置。

我尝试做的事情: 加载我的安全配置

@ContextConfiguration(classes = {SecurityConfigImpl.class})
public class PeopleGQLApiSecutiryTest {
    private final PersonService personService = mock(PersonService.class);
    private final PeopleGQLApi peopleGQLApi = new PeopleGQLApi(personService);

    @Test
    @WithAnonymousUser
    void itShouldCreateNewPerson() {
        when(personService.createNewPerson(any(Person.class))).thenReturn(new Person());
        // this should fail!
        peopleGQLApi.createPerson(
                Person.LevelEnum.WEAK,
                // rest of the arguments
        );
    }
}

这个应该会失败(通过抛出期望或类似的东西),因为 create person 是 ROLE_ADMIN.

的安全函数

注意:这是一个 GraphQL 突变

    @MutationMapping("createPerson")
    @Secured({"ROLE_ADMIN"})
    public Person createPerson(
       @Argument("level") Level level,
             // rest of the arguments
    ) {
             // method implementation
      }

我无法使用完全成熟的 @SpringBootTest,因为我还必须提供超出本次测试范围的 mongodb 配置。

我想你要找的词是@WithMockUser

您可以使用 @WithMockUser(authorities = "ROLE_ADMIN") 之类的东西来模拟具有此角色的用户

另外,对于更多调整,您可以使用 Spring 安全上下文

SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("username", "password"));
SecurityContextHolder.setContext(securityContext);

并且您可以将任何权限添加到您的安全上下文或读取它们。

最好将它们添加到 securityUtil class 以便在多种情况下使用。

请确保您有断言来验证测试用例中的未授权请求