在spring-boot 2.1.1中使用spring-security为WebMvcTest配置MockMvc

avi*_*tix 5 spring-security spring-boot mockmvc junit5

WebMvcTest在Spring-Boot 2.1.1中与MockMvcSpring-Security 5.1.2 一起运行时是否存在任何已知问题?因为我无法正常工作-但是也许您看到我错过了什么。

这是我使用Junit5进行的设置:

RestController:

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

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

}
Run Code Online (Sandbox Code Playgroud)

测试

@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());
  }
}
Run Code Online (Sandbox Code Playgroud)

当我像这样运行它时,我总是收到404的请求:

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.
Run Code Online (Sandbox Code Playgroud)

如果我卸下@PreAuthorize("hasRole('ADMIN')")REST控制器,一切正常,我得到200。

我还尝试为此测试禁用spring-security(这不是我的最爱,但至少可以运行我的测试)。

因此,我将测试类设置更改为以下内容:

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

但这似乎并没有禁用安全性,而是导致的新错误,springSecurityFilterChain并且查看AutoConfigureMockMvc您的javadoc 会发现对安全标记的注释@deprecated since 2.1.0 in favor of Spring Security's testing support。我找不到确切含义的具体信息。

有人知道我的错误在哪里吗?谢谢你的帮助!