3

I would like to inject principal object in controller test, but it is always null. Im already setting the authentication object to SecurityContextHolder

SecurityContextHolder.getContext().setAuthentication(authentication);

this is my setup before

@Autowired
    private WebApplicationContext wac;

 @Before
    public void abstractControllerSetUp() {
        securityUser = getPrincipal();
        authentication = logIn();
        mockMvc = webAppContextSetup(wac).build();
    }

but when I call

mockMvc.perform(put("/partner/notifications/activate")
                .content(toJson(command))
                .with(user(securityUser))
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());

the principal is alwyas null, it works when app running.

@PutMapping("/activate")
    public void activateNotification(@RequestBody NotificationCommand command, @AuthenticationPrincipal Principal principal) {
filemonczyk
  • 125
  • 6

2 Answers2

2

In Spring 4.3.2, MockMvcRequestBuilders has a method called principal(). Use that instead of with(user()).

mockMvc.perform(put("/partner/notifications/activate")
            .content(toJson(command))
            .principal(securityUser)
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk());
2

Try the following :

User user = new User(userName,userPassword, AuthorityUtils.createAuthorityList("YOUR_ROLES...."));
TestingAuthenticationToken testingAuthenticationToken = new TestingAuthenticationToken(user,null);

Then

mockMvc.perform(put("/partner/notifications/activate").principal(testingAuthenticationToken))
mkane
  • 880
  • 9
  • 16