Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting principal in controller test

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) {
like image 621
filemonczyk Avatar asked Oct 20 '25 13:10

filemonczyk


1 Answers

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());
like image 197
cykedelielic Avatar answered Oct 23 '25 02:10

cykedelielic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!