Spring TestRestTemplate doesn't work automatically

I am currently using Spring Boot 1.5.4 along with Junit 5 and Java 8.

I want to set up integration tests for multiple records that are stored in a csv file using Junit ParameterizedTest.

Here is the code:

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

    @Autowired
    private TestRestTemplate template;

    @ParameterizedTest
    @MethodSource(names = "vehicles")
    void nonRegressionTests(EDIVehicle vehicle) {
        ResponseEntity<Vehicle> v = template.getForEntity("/match/" + vehicule.getId(), Vehicle.class);
        Assert.assertNotNull(v);
    }

    private static Stream<EDIVehicle> vehicles() throws IOException {
        InputStream is = new ClassPathResource("/entries.csv").getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        return br.lines().map(toVehicle);
    }

    private static Function<String, EDIVehicle> toVehicle = (line) -> {
        String[] p = line.split("\\|");
        return new EDIVehicle(p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9], p[10], p[11], p[12]);
    };
}

      

I know from the documentation that:

If you use @SpringBootTest annotation, TestRestTemplate is automatically available and can be @Autowired in your test.

The thing is, I am using SpringBootTest annotation, but when I run tests, TestRestTemplate is null all the time. I may have missed something.

EDIT: I have the same problem while adding @RunWith annotation (SpringRunner.class)

+3


source to share


3 answers


I ended up using a dependency on the following repo: github.com/sbrannen/spring-test-junit5 as @LucasP mentioned

Since there is no first class support for JUnit 5 in Spring 4.3 and below, this helped me autowiring the Spring TestRestTemplate correctly using @ExtendWith(SpringExtension.class)

in my test class.



The next step is to directly use Spring Boot 2.0 to better support JUnit 5.

+2


source


@SpringBootTest

not fully compatible with JUnit 5. However, you can work around this by using the following test declaration:

@RunWith(JUnitPlatform.class)
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = RANDOM_PORT)
class MatchingIT {...}

      



Note. You must upgrade spring-boot-starter-test

to 2.0.0.M1

to use org.springframework.test.context.junit.jupiter.SpringExtension

(the easiest way: start.spring.io to create dependent 2.0.0.M1 project and obtain the necessary dependencies maven / gradle here).

+1


source


I think what you are missing @RunWith(SpringRunner.class)

, and also make sure that your class that initializes the context (usually the one that contains the main method) is annotated @SpringBootApplication

(else @SpringBootTest

does not find the context to load for the test.

-1


source







All Articles