2017-07-14 118 views
0

我想为使用JWT身份验证的应用程序编写集成测试。Java/Groovy集成测试受保护资源

@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 
    } 

但我需要放置一个令牌头。怎么可以做到这一点?

回答

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[]