Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

How do you mock a Springframework security principal for testing spring MVC controllers?

  1. Create a spring security principal
  2. Create a spring authentication
  3. Add the spring security authentication to the security context

The last step should not be needed because MockMVC has a method to set the principal (line 16). However, we had an annotation that used the security principal to retrieve the username that was then used to retrieve another object. We couldn’t find the value there. We set the spring security authentication manually via the spring security context (line 19).

public class TestActivityController {
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    public void setup() {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();

    public void testInitialDisplay() throws Exception {
        User user = new User("screen011","", AuthorityUtils.createAuthorityList("ROLE_PATRON"));
        TestingAuthenticationToken testingAuthenticationToken = new TestingAuthenticationToken(user,null);


February 27th, 2014

Posted In: Java, MockMVC, Spring, Spring MVC, Spring Security

Tags: , , , , , , , , , , , , , ,


LinkedIn Auto Publish Powered By :