Home » Java » Enterprise Java » Mocking Spring Security Context for Unit Testing

About Arpit Aggarwal

Arpit Aggarwal
Arpit is a Consultant at Xebia India. He has been designing and building J2EE applications since more than 6 years. He is fond of Object Oriented and lover of Functional programming. You can read more of his writings at aggarwalarpit.wordpress.com

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 {

	public void setupMock() {

	public void mockApplicationUser() {
		ApplicationUser applicationUser = mock(ApplicationUser.class);
		Authentication authentication = mock(Authentication.class);
		SecurityContext securityContext = mock(SecurityContext.class);

Reference: Mocking Spring Security Context for Unit Testing from our JCG partner Arpit Aggarwal at the Arpit Aggarwal blog.
(0 rating, 0 votes)
You need to be a registered member to rate this.
3 Comments Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Leave a Reply

2 Comment threads
1 Thread replies
Most reacted comment
Hottest comment thread
3 Comment authors
Ajoy BhatiaArpit AggarwalAngel Luis Fernandez Benot Recent comment authors

This site uses Akismet to reduce spam. Learn how your comment data is processed.

newest oldest most voted
Notify of
Angel Luis Fernandez Benot
Angel Luis Fernandez Benot

Thanks very much for that information, it save my today.

Arpit Aggarwal

Nice to hear this Angel Luis Fernandez Benot, I appreciate if you share your feedback on the original post as well – https://aggarwalarpit.wordpress.com/2017/05/17/mocking-spring-security-context-for-unit-testing/

Ajoy Bhatia
Ajoy Bhatia

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

can be replaced by: