簡體   English   中英

Spring TestRestTemplate沒有正確自動裝配

[英]Spring TestRestTemplate not autowiring correctly

我目前正在使用Spring Boot 1.5.4以及Junit 5和Java 8。

我想使用Junit的ParameterizedTest對存儲在csv文件中的多個條目設置集成測試。

這是代碼:

@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]);
    };
}

我從文檔中知道:

如果您正在使用@SpringBootTest注釋,則TestRestTemplate會自動可用,並且可以@Autowired進入您的測試。

問題是我使用SpringBootTest注釋,但是當我運行測試時,TestRestTemplate始終為null。 也許我錯過了什么。

編輯:我添加@RunWith(SpringRunner.class)注釋時確實有同樣的問題

我最終使用了以下repo中的依賴項: github.com/sbrannen/spring-test-junit5如上所述@LucasP

由於在Spring 4.3及以下版本中沒有對JUnit 5的第一類支持,因此它幫助我在我的測試類上使用@ExtendWith(SpringExtension.class)正確地自動裝配了Spring TestRestTemplate。

下一步是直接使用Spring Boot 2.0來更好地支持JUnit 5。

@SpringBootTest與JUnit 5不完全兼容。但是,您可以使用下一個測試聲明來解決此問題:

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

注意:您必須將spring-boot-starter-test版本升級到2.0.0.M1才能使用org.springframework.test.context.junit.jupiter.SpringExtension (最簡單的方法是使用start.spring。 io用於生成依賴於2.0.0.M1的項目並從那里獲取所需的maven / gradle依賴項。

我認為你缺少@RunWith(SpringRunner.class)並且還要確保初始化上下文的類(通常是包含main方法的類)具有@SpringBootApplication注釋(否則@SpringBootTest沒有找到要加載的上下文為了測試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM