How to Mock SecurityContextHolder to perfrom JUnit tests on Spring Controller ?

Use the following code to mock SecurityContextHolder, by adding the Authentication(principal) object to it at startup.

public class SpringSecurityTest {
            @Before
            public void onSetUp() {
                // add principal object to SecurityContextHolder
                User user = new User();
                /* fill user object */

                Authentication auth = new UsernamePasswordAuthenticationToken(user,null);

                SecurityContextHolder.getContext().setAuthentication(auth);

            }

            @Test
            public void testAuthentication(){}
}

Search