Тест Springboot не может автоматически подключить TestRestTemplate при использовании junit5 - PullRequest
1 голос
/ 11 марта 2020

Я использую Springboot версии 2.2.2.RELEASE.

Я пытаюсь добавить тесты с junit5, вот как я его установил в 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"

И вот мой тестовый класс:

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

}

Проблема в том, что restRestTemplate имеет значение null. Единственный способ, которым это работает, это когда я использую:

@ RunWith (SpringRunner.class)

Однако, для моего понимания, это для поддержки junit4, верно?

Я использую неизнашиваемый TestRestTemplate (org.springframework.boot.test.web.client.TestRestTemplate).

Я также пытался добавить следующее, но это тоже не сработало:

@ ExtendWith (SpringExtension.class)

Чего мне не хватает?

Спасибо.

1 Ответ

2 голосов
/ 11 марта 2020

Убедитесь, что весь ваш тест использует аннотации, связанные с JUnit 5. Возможно, ваша аннотация @Test все еще использует 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);
  }
}
...