Wicaledon
Wicaledon

Reputation: 810

Rest Assured & Spring - Value Becomes Null After First Test

I have a strange problem. I've written my API and I just wanted to test it.

I wrote a simple test code by using Restassured:

package com.example.restservicetest;

import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;

import java.util.*;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class RestServiceTestApplicationTests {

    @LocalServerPort
    private int port;

    private Response response;
    private List<Object> folderList;

    @Test
    public void getWholeFolders() {
        response = RestAssured.given().port(port).when().get("/api/opening").then().statusCode(200).extract().response();
        folderList= response.jsonPath().getList("folders");
    }

    @Test
    public void getRandomFolderNumber() {
        Random rand = new Random();
        RestAssured.given().port(port).when().get("/api/opening/folder/" + rand.nextInt(folderList.size()-1)).then().statusCode(200);
    }

}

When I debug my test, at the end of first getWholeFolders test, I see that folderList is not empty as I expected. My whole folder list is assigning to it.

But when the time is for 2nd test getRandomFolderNumber, I see that folderList becomes null.

Why does it become null?

Upvotes: 0

Views: 647

Answers (1)

lucas-nguyen-17
lucas-nguyen-17

Reputation: 5917

As Andriy mentiond in comment, JUnit Jupiter will use a default lifecycle mode, it means JUnit creates a new instance of each test class before executing each test method TestInstance.Lifecycle.PER_METHOD.

To change that, you change PER_METHOD --> PER_CLASS (basically means one instance of test class for all test method).

One more subtle thing, you need to set order for test method to make sure getRandomFolderNumber always run after getWholeFolders

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class RestServiceTestApplicationTests {
    ...

    @Test
    @Order(1)
    public void getWholeFolders() {
        ...
    }

    @Test
    @Order(2)
    public void getRandomFolderNumber() {
        ...
    }

}

Upvotes: 1

Related Questions