Reputation: 4830
I write integration test for protected resources and therefore I have to log in, get the token from request and in the next test use this token.
I wanted to do it like below:
@Autowired
private TestRestTemplate restTemplate
private String token
def 'login'() {
given:
final UserData userData = new UserData("User", "Password")
when:
def response = restTemplate.postForEntity('/login', userData, Object)
// assign token to variable
this.token = response.getHeaders().get("Authorization")
then:
response.getStatusCode() == HttpStatus.OK
response.getHeaders().get("Authorization") != null
}
And I wanted to use assigned token in the next test, but I get NUllPointerException:
def 'request test'() {
final MultiValueMap<String, String> headers = new LinkedMultiValueMap<>()
headers.add("Authorization", token)
final HttpEntity request = new HttpEntity(headers)
when:
def response = rest.exchange('/test', HttpMethod.GET, request, new ParameterizedTypeReference<String>() {})
then:
response.getStatusCode() == HttpStatus.OK
}
In this test token has null value. Why and how can I resolve this problem?
Upvotes: 1
Views: 1446
Reputation: 13222
Normal fields are not shared between test executions, if you want to share them you need to annotate the field with @spock.lang.Shared
. If you want to execute your tests in a deterministic order, then you need to annotate your spec with @spock.lang.Stepwise
.
@Stepwise
class Test {
@Shared
String token
def test1() {/* ... */ }
def test2() {/* ... */ }
}
Upvotes: 1