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

时间:2018-12-21 12:07:47

标签: spring-boot spring-security junit5 mockmvc

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

这是我使用Junit5的设置:

RestController:

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

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

}

测试

@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());
  }
}

当我这样运行时,我总是收到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.

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

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

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

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

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

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

0 个答案:

没有答案