• spring-boot-starter-parent:2.7.0
  • java 8
  • code:
@ExtendWith(SpringExtension.class)
@WebMvcTest(controllers = ReservationResource.class)
@DisplayName("Testing ReservationResource Web layer")
class ReservationResourceMvcTest {

    @Test
    @WithMockUser(roles = "USER", username = TEST_NET_ID)
    @DisplayName("deleteReservationByOwner mock MVC with mock user")
    void deleteReservationByOwner() throws Exception {

        this.mockMvc
              .perform(delete(Util.PATH_RESERVATION + "/1"))
              .andExpect(status().is2xxSuccessful());

        verify(reservationService).deleteReservationById(1L, TEST_NET_ID);
    }
}
  • when I check principal in ReservationResource it is NULL

Comment From: wilkinsona

Thanks for the report. We have tests, such as this one, that verifies the behavior of @WithMockUser and @WebMvcTest. Unfortunately, an incomplete code snippet is insufficient for us to diagnose what differences are causing things not to work for you. If you would like us to spend some more time investigating, please spend some time providing a complete yet minimal sample that reproduces the problem. You can share it with us by pushing it to a separate repository on GitHub or by zipping it up and attaching it to this issue.

Comment From: sysmat

  • WebSecurityConfigurerAdapter is deprecated so I move to SecurityFilterChain
  • in WebMvcTest if I don't mock SecurityFilterChain then the client doesn't hit the REST endpoint
  • in WebMvcTest if I use @MockBean SecurityFilterChain apiSecurity then in REST endpoint method principle is NULL
@DeleteMapping("/{id}")
public void deleteReservationByOwner(@PathVariable Long id, Principal principal) {
        System.out.println("deleteReservationByOwner:principal="+principal);
        this.reservationService.deleteReservationById(id, principal.getName());
}
  • @MockBean SecurityFilterChain apiSecurity log is:
25-05-2022 11:32:21.694 &amp#27;[35m[main]&amp#27;[0;39m &amp#27;[34mINFO &amp#27;[0;39m s.a.j.security.RoomRedirectFilter.doFilterInternal(31) - isRedirect=false
deleteReservationByOwner:principal=null
25-05-2022 11:32:21.751 &amp#27;[35m[main]&amp#27;[0;39m &amp#27;[1;31mERROR&amp#27;[0;39m s.a.j.e.ResourcesExceptionHandler.generalException(55) - error msg=null

MockHttpServletRequest:
      HTTP Method = DELETE
      Request URI = /rr/1
       Parameters = {}
          Headers = []
             Body = null
    Session Attrs = {SPRING_SECURITY_CONTEXT=SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=org.springframework.security.core.userdetails.User [Username=test@test.si, Password=[PROTECTED], Enabled=true, AccountNonExpired=true, credentialsNonExpired=true, AccountNonLocked=true, Granted Authorities=[ROLE_USER]], Credentials=[PROTECTED], Authenticated=true, Details=null, Granted Authorities=[ROLE_USER]]]}

Handler:
             Type = si.arnes.jitsireservations.resource.ReservationResource
           Method = si.arnes.jitsireservations.resource.ReservationResource#deleteReservationByOwner(Long, Principal)

Async:
    Async started = false
     Async result = null
  • is there any migration guide for WebMvcTest
  • https://docs.spring.io/spring-security/reference/5.7.0-M2/servlet/configuration/java.html#_multiple_httpsecurity here test suite is not covered

Comment From: wilkinsona

Your problem may be a duplicate of #31162 but it's impossible to say for certain without a sample. If you would like us to look into this further, please provide one.

Comment From: sysmat

  • demo, where in rest endpoint Principle is NULL

filter.zip

Comment From: wilkinsona

Thanks for the sample. Your SecurityConfig class is a plain @Configuration class so it isn't included in a @WebMvcTest. As described in the javadoc of @WebMvcTest, you need to use @Import to create any additional collaborators that are needed by your test:

@Import(SecurityConfig.class)
@WebMvcTest(controllers = RestEndPoint.class)
@DisplayName("Testing REST end point")
public class MvcTest {

You should also remove your mock apiSecurity bean. With these changes in place, your test passes.

Comment From: sysmat

@wilkinsona thx, it would be really nice to have documentation

Comment From: wilkinsona

We already have some as a result of these changes in 2.5.11 for https://github.com/spring-projects/spring-boot/issues/16088.