我想为我的应用程序编写使用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
}
但是我需要在标题中放置一个标记。怎么办?
答案 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[]
。