How to mock security context in tests if I disabled authorizarion

9k views Asked by At

I have tests like this:

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

    @Autowired
    private TestRestTemplate restTemplate;
    ....

In tests I disabled authentification/authorizaton

But in code I use following:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

But it is reason why tests fails.

How can I mock it my tests?

P.S.

This one doesn't work:

@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(..

SecurityContextHolder.getContext().getAuthentication() returns null in code

and this one too:

@Autowired
private TestRestTemplate restTemplate;
@Test
@WithMockUser(username = "aUser", roles = { "ADMIN" })
public void testUpdateWithoutNameAndEmail() {
   ...
1

There are 1 answers

5
glytching On

You can mock Spring's Authentication:

Authentication authentication = Mockito.mock(Authentication.class);

And tell Spring's SecurityContextHolder to store this Authentication instance:

SecurityContext securityContext = Mockito.mock(SecurityContext.class);
Mockito.when(securityContext.getAuthentication()).thenReturn(auth);
SecurityContextHolder.setContext(securityContext);

Now, if your code needs Authentication to return something (the user name perhaps) you just set some expectations on the mocked Authentication instance in the usual way e.g.

Mockito.when(authentication.getName()).thenReturn("aName");

There's also a Spring test annotation (org.springframework.security.test.context.support.WithMockUser) which does this for you...

@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"
    // ...
}