Search code examples
spring-bootspring-boot-test

Springboot test fails to autowire TestRestTemplate when using junit5


I am using springboot version 2.2.2.RELEASE.

I am trying to add tests with junit5, here is how I set it in my build.gradle:

testImplementation('org.springframework.boot:spring-boot-starter-test') {
    exclude group: 'junit', module: 'junit'
}
testImplementation "org.junit.jupiter:junit-jupiter-api:5.5.2"
testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:5.5.2"

And here is my test class:

//@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT, classes = UserServiceApplication.class)
@ActiveProfiles("it")
public class UserControllerIntegrationTest {
    @Autowired
    private TestRestTemplate testRestTemplate;

}

The problem is that restRestTemplate is null. The only way it works is when I use:

@RunWith(SpringRunner.class)

However, for my understanding this is for support of junit4, right?

I am using the not deprecated TestRestTemplate (org.springframework.boot.test.web.client.TestRestTemplate).

I also tried to add the following, but it didn't work too:

@ExtendWith(SpringExtension.class)

What am I missing?

Thank you.


Solution

  • Make sure your whole test is using JUnit 5 related annotations. Maybe your @Test annotation is still using JUnit 4.

    The following example works for JUnit 5 and Spring Boot:
    
    import org.junit.jupiter.api.Test;
    import org.junit.jupiter.api.extension.ExtendWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.boot.test.web.client.TestRestTemplate;
    import org.springframework.test.context.junit.jupiter.SpringExtension;
    
    import static org.junit.jupiter.api.Assertions.assertNotNull;
    
    @ExtendWith(SpringExtension.class)
    @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = YourApplication.class)
    public class TestOne {
    
      @Autowired
      private TestRestTemplate testRestTemplate;
    
      @Test
      public void test() {
        assertNotNull(testRestTemplate);
      }
    }