5

is there any known issue with running a WebMvcTest in Spring-Boot 2.1.1 together with MockMvc and Spring-Security 5.1.2? Because I cannot get it to work - but maybe you see where I missed something.

Here is my setup with Junit5:

RestController:

@RestController
@RequestMapping("/api/foo")
public class FooRestController {
...

  @GetMapping("/{id}")
  @PreAuthorize("hasRole('ADMIN')")
  public String getFoo(@PathVariable("id") long id) {
    //do something
  }

}

Test

@ExtendWith(SpringExtension.class)
@AutoConfigureMockMvc
@WebMvcTest(value = FooRestController.class)
public class FooRestControllerTest {

  @Autowired
  private WebApplicationContext context;

  protected MockMvc mockMvc;

  @BeforeEach
  public void setup() {
    this.mockMvc = MockMvcBuilders
      .webAppContextSetup(this.context)
      .apply(springSecurity())
      .build();
  }

  @Test
  @WithMockUser(roles = "ADMIN")
  public void testFoo() throws Exception {

    MockHttpServletResponse apiResponse = mockMvc.perform(get("/api/foo/42")
      .contentType(MediaType.APPLICATION_JSON)
    )
    .andDo(print())
    .andReturn()
    .getResponse();

    assertThat(apiResponse.getStatus())
      .isEqualTo(HttpStatus.OK.value());
  }
}

When I run it like this I always receive a 404 for my request:

MockHttpServletResponse:
       Status = 404
       Error message = null
       Headers = {Set-Cookie=[XSRF-TOKEN=683e27a7-8e98-4b53-978d-a69acbce76a7; Path=/], X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0]}
 Content type = null
         Body = 
Forwarded URL = null
Redirected URL = null
      Cookies = [[Cookie@1f179f51 name = 'XSRF-TOKEN', value = '683e27a7-8e98-4b53-978d-a69acbce76a7', comment = [null], domain = [null], maxAge = -1, path = '/', secure = false, version = 0, httpOnly = false]]

org.opentest4j.AssertionFailedError: 
Expecting:
<404>
to be equal to:
<200>
but was not.

If I remove @PreAuthorize("hasRole('ADMIN')") in my REST-controller, everything works fine and I get my 200.

I also tried to disable spring-security for this test (which isn´t my favourite, but at least then my test would run).

So I changed my test-class-setup to the following:

@ExtendWith(SpringExtension.class)
@AutoConfigureMockMvc(secure = false)
@WebMvcTest(value = FooRestController.class, excludeAutoConfiguration = SecurityAutoConfiguration.class)
public class FooRestControllerTest {
   ... same as before
}

But this does not seem to disable the security but caused new errors with the springSecurityFilterChainand looking at the javadoc of AutoConfigureMockMvc you will find a comment for the secure-flag saying @deprecated since 2.1.0 in favor of Spring Security's testing support. I couldn´t find anything concrete about what that means exactly.

Does anybody has an idea, where my mistake is? Thanks for your help!

digital-h
  • 301
  • 3
  • 11
  • 1
    You can read [this issue page](https://github.com/spring-projects/spring-boot/issues/14227) explaining why secure-flag has been deprecated, and what to use instead (`@WithMockUser`). – mczerwi Dec 21 '18 at 15:20
  • 1
    Thanks a lot for this link. This explains a lot - but unfortunately it will not solve my problem, as I already use `@WithMockUser` as you can see in my example. – digital-h Dec 22 '18 at 19:02
  • this helped me to turn-off the security: `@AutoConfigureMockMvc(addFilters = false)` – Andrey Mar 03 '21 at 14:20

0 Answers0