2

我正在尝试测试家庭控制器

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

}

结果

预期结果:

<"[你好世界!]">

实际结果:

<"{"timestamp":1501100448216,"status":401,"error":"Unauthorized","message":"访问此资源需要完全认证","path":"/"}]">

我错过了什么吗?

4

1 回答 1

1

尝试将以下内容添加到您的测试类中:

@TestExecutionListeners(mergeMode = MergeMode.MERGE_WITH_DEFAULTS, listeners = {
        WithSecurityContextTestExecutionListener.class
})

如果你没有它,还有以下依赖项:

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <scope>test</scope>
</dependency>

@TestExecutionListenersSpring security 需要一个额外的侦听器,默认情况下测试中不存在该侦听器,因此您需要通过在模式中指定注释来告诉 spring 添加它,merge以便它将当前列出的侦听器与您要添加的侦听器合并 - 在这种情况下WithSecurityContextTestExecutionListener

于 2017-07-27T06:35:42.960 回答