How To Mock SecurityContextHolder in Spring Security using Mockito?1 min read


Test-driven development is a pretty awesome design process. And while building your code, you may want to mimic the logged-in user.

In Spring Security, the logged-in user principal is stored inside the Authentication object. This Authentication object can be accessed from any part of your application using SecurityContextHolder.

The SecurityContextHolder is a singleton class that holds the SecurityContext.

So, in the test case, we should never actually mock the SecurityContextHolder rather mock the SecurityContext and Authentication object that it holds.

Let’s see how you can perform the mocking. You can simply copy & paste the below method inside your test class and call it the test method or setup. Just provide the logged-in user that will be returned on calling authentication.getPrincipal() in your actual code.

private void mockAuthentication() {
    Authentication auth = mock(Authentication.class);

    when(auth.getPrincipal()).thenReturn(buildLoggedInUser());

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

Hope this helps. If you have any problem, just comment below. The comment is the fastest way to reach me.


  • Article By: Varun Shrivastava

  • Varun Shrivastava is an innovative Full Stack Developer at ThoughtWorks with around 4 years of experience in building enterprise software systems in finance and retail domain. Experienced in design, development, and deployment of scalable software. He is a passionate blogger and loves to write about philosophy, programming, tech and relationships. This is his space, you can get in touch with him here anytime you want.
  • Website Search



  • Grab the Deal Now!

    Hostgator  Starting @$3.95/mo

  • DigitalOcean Free Credits!