Java / Groovy集成测试受保护的资源

时间:2017-07-14 08:42:58

标签: java spring groovy spring-security integration-testing

我想为我的应用程序编写使用JWT身份验证的集成测试。

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.POST, "/login").permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilterBefore(new MyJWTLoginFilter("/login", authenticationManager()), UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(new MyJWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

我的常规测试:

 @ContextConfiguration
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Stepwise
class MyControllerSpec extends Specification {

    @Autowired
    private TestRestTemplate testRestTemplate

def 'findAll() test'() {
        when:
            def result = testRestTemplate.getForEntity('/findAll', User[])

        then:
            result.getStatusCode() == HttpStatus.OK
            result.getBody().toList().size() == 1
    }

但是我需要在标题中放置一个标记。怎么办?

1 个答案:

答案 0 :(得分:0)

您可以设置请求标头,HttpEntity传递给RestTemplate.exchange()方法。请考虑以下测试用例:

def "findAll() test"() {
    given:
    final RestTemplate restTemplate = new RestTemplate()
    final MultiValueMap<String, String> headers = new LinkedMultiValueMap<>()
    headers.add("Authorization", "Bearer .....")
    final HttpEntity request = new HttpEntity(headers)

    when:
    def response = restTemplate.exchange('/findAll', HttpMethod.GET, request, new ParameterizedTypeReference<List<User>>(){})

    then:
    response.getStatusCode() == HttpStatus.OK

    and:
    !response.getBody().isEmpty()
}

您还可以使用ParameterizedTypeReference将返回类型指定为List<User>,而不是User[]