Mocking Spring Security Context for Unit Testing

Today, while writing unit test case for one of the Java method which looks like below:

public ApplicationUser getApplicationUser() {
	ApplicationUser applicationUser = (ApplicationUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	return applicationUser;
}

I want to mock Spring Security Context to get the Principal, to achieve the same I mocked each level of method calls as follows:

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.mock;
import org.mockito.MockitoAnnotations;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import com.arpit.security.user.ApplicationUser;

public class BaseTest {

	@Before
	public void setupMock() {
		MockitoAnnotations.initMocks(this);
	}

	@Test
	public void mockApplicationUser() {
		ApplicationUser applicationUser = mock(ApplicationUser.class);
		Authentication authentication = mock(Authentication.class);
		SecurityContext securityContext = mock(SecurityContext.class);
		when(securityContext.getAuthentication()).thenReturn(authentication);
		SecurityContextHolder.setContext(securityContext);
		when(SecurityContextHolder.getContext().getAuthentication().getPrincipal()).thenReturn(applicationUser);
	}

}

4 thoughts on “Mocking Spring Security Context for Unit Testing

  1. The last line of the test method, i.e.:

    `when(SecurityContextHolder.getContext().getAuthentication().getPrincipal()).thenReturn(applicationUser);`

    can be replaced by:

    `when(authentication.getPrincipal()).thenReturn(applicationUser);`

    Liked by 1 person

Leave a comment