如果我禁用了authorizarion,如何在测试中模拟安全上下文

gst*_*low 3 java spring integration-testing spring-security security-context

我有这样的测试:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
@ActiveProfiles("test")
public class MyTests {

    @Autowired
    private TestRestTemplate restTemplate;
    ....
Run Code Online (Sandbox Code Playgroud)

在测试中,我禁用了身份验证/授权

但在代码中我使用以下内容:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Run Code Online (Sandbox Code Playgroud)

但这是测试失败的原因.

我怎么能模拟我的测试?

PS

这个不起作用:

@Test
public void testUpdateWithoutNameAndEmail() {
    Authentication authentication = Mockito.mock(Authentication.class);
    SecurityContext securityContext = Mockito.mock(SecurityContext.class);
    Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
    SecurityContextHolder.setContext(securityContext);
    Mockito.when(authentication.getName()).thenReturn("aName");

    restTemplate.exchange(..
Run Code Online (Sandbox Code Playgroud)

SecurityContextHolder.getContext().getAuthentication() 在代码中返回null

而且这个也是:

@Autowired
private TestRestTemplate restTemplate;
@Test
@WithMockUser(username = "aUser", roles = { "ADMIN" })
public void testUpdateWithoutNameAndEmail() {
   ...
Run Code Online (Sandbox Code Playgroud)

gly*_*ing 6

你可以模仿Spring的Authentication:

Authentication authentication = Mockito.mock(Authentication.class);
Run Code Online (Sandbox Code Playgroud)

并告诉Spring SecurityContextHolder存储此Authentication实例:

SecurityContext securityContext = Mockito.mock(SecurityContext.class);
Mockito.when(securityContext.getAuthentication()).thenReturn(auth);
SecurityContextHolder.setContext(securityContext);
Run Code Online (Sandbox Code Playgroud)

现在,如果您的代码需要Authentication返回一些东西(可能是用户名),您只需Authentication按常规方式对模拟实例设置一些期望,例如

Mockito.when(authentication.getName()).thenReturn("aName");
Run Code Online (Sandbox Code Playgroud)

还有一个Spring测试注释(org.springframework.security.test.context.support.WithMockUser)为你做这个...

@Test
@WithMockUser(username = "aUser", roles = { "anAuthority" })
public void aTest(){
    // any usage of `Authentication` in this test will get an instance withe the user name "aUser" and a granted authority "anAuthority"
    // ...
}
Run Code Online (Sandbox Code Playgroud)

  • 1.你明白我使用TestRestTemplate进行测试吗?SecurityContextHolder.getContext().getAuthentication() 在我的主题更新中返回 null 等于 NPE (2认同)