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.