In this example we'll show you how to mock Security Context and Authentication in Spring boot test. This could be needed in case that in your code you're for example getting some value from your token like it was a case for me. I needed the user_name parameter nested in decoded details of Oauth2AuthenticationDetails. We'll be using Mockito and it's mock and when methods to firstly mock Oauth2AuthenticationDetails and then build up until we get to the SecurityContextHolder.

Here's the code example:

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;


.....
Map<String, Object> details = new HashMap<String, Object>();
details.put("user_name", "someusername");
OAuth2AuthenticationDetails oauthDetails = mock(OAuth2AuthenticationDetails.class);
when(oauthDetails.getDecodedDetails()).thenReturn(details);
Authentication authentication = mock(Authentication.class);
when(authentication.getDetails()).thenReturn(oauthDetails);

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