0

I have a Spring Controller that contains a logout endpoint

@PostMapping("/logout")
public ResponseEntity<Void> logout() {
    var request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
    try {
        request.logout();
        return new ResponseEntity<>(HttpStatus.OK);
    } catch (ServletException e) {
        log.error("Unable to logout");
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

How can I test this using mockmvc ?

What I have so far is this piece of code, but I don't know how to test that the request.logout() was called (what are its effects?).

mvc.perform(MockMvcRequestBuilders.post("/logout").principal(principal)).expect(??)
simo
  • 33
  • 2

1 Answers1

0

From this Post:

Using spring security test package, try this code:

getMockMvc().perform(get("http://login.com").principal(principal))
        .andExpect(status().isOk()));

Or:

getMockMvc().perform(get("http://your-url.com").principal(new UserPrincipal("TEST_USER_ID"))).andExpect(status().isOk()));
Med Elgarnaoui
  • 1,612
  • 1
  • 18
  • 35
  • 1
    Well the part I'm interested in testing is not really the status code but the side effect that is produced by `request.logout()`. In other words, I would want the test to fail if I comment out `request.logout()`. Your snippet doesn't achieve that. – simo Mar 30 '21 at 19:46
  • Ok take a look at the post I montioned in the solution, you can use this `final ResultActions resultActions = this.mockMvc.perform(sessionLogout());` from @Nagy Attila solution – Med Elgarnaoui Mar 30 '21 at 19:59
  • I'm not sure how it relates, can you please edit your answer then ? – simo Mar 30 '21 at 20:39