【发布时间】:2018-01-02 08:30:38
【问题描述】:
我正在尝试测试家庭控制器
@RequestMapping("/")
@ResponseBody
String home() {
return "Hello World!";
}
我使用 spring security 作为用户名“user”并默认测试为密码,但 @PreAuthorize 不起作用
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@PreAuthorize("hasRole('ADMIN')")
public class HomeControllerTest {
@Autowired
private TestRestTemplate restTemplate;
@Test
@WithMockUser(username = "user", password = "test", roles = "ADMIN")
public void home() throws Exception {
String body = this.restTemplate.getForObject("/", String.class);
assertThat(body).isEqualTo("Hello World!");
}
}
结果
预期结果:
实际结果:
我错过了什么吗?
【问题讨论】:
-
你正在调用一个真正的控制器,所以在这里使用
@WithMockUser几乎没用。仅当您直接在控制器上调用home()方法时,这才有效。假设您具有用于登录的基本身份验证设置,您应该将凭据与您的请求一起发送。此外,您的测试用例上的@PreAuthorize也不会取得任何成果。
标签: spring spring-boot junit spring-test spring-security-test