自从我从1.x迁移到Spring Boot 2.0.5后,没有禁用安全性的意思,我无法在模拟MVC测试中使测试角色起作用:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ApplicationsControllerShould {
...
@Autowired
private MockMvc mockMvc;
private ObjectMapper mapper = new ObjectMapper();
@Test
@WithMockUser(roles = "ADMIN")
public void handle_CRUD_for_applications() throws Exception {
Application app = Application.builder()
.code(APP_CODE).name(APP_NAME)
.build();
mockMvc.perform(post("/applications")
.accept(MediaType.APPLICATION_JSON_UTF8)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(mapper.writeValueAsString(app)))
.andExpect(authenticated())
.andExpect(status().isOk()); // failure 403!
...
我的控制器端点甚至没有被保护!
@RestController
@RequestMapping("/applications")
public class ApplicationsController {
...
@PostMapping
public Application addApplication(@RequestBody Application application) {
Assert.isTrue(!applicationsDao.existsById(application.getCode()), "Application code already exists: " + application.getCode());
return applicationsDao.save(application);
}
}
我在测试中使用了会话(#authenticated在去掉@WithMockUser注释后失效)和角色(ROLE_ADMIN在跟踪中可见),但是我的请求被拒绝了,我不明白哪里出了问题。 感谢任何意见!