【发布时间】:2017-11-15 12:24:20
【问题描述】:
我目前正在使用 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 始终为空。也许我错过了什么。
编辑:我在添加 @RunWith(SpringRunner.class) 注释时确实遇到了完全相同的问题
【问题讨论】:
-
您使用的是 JUnit 5 吗?我认为 Spring Boot 还没有为 JUnit 5 提供一流的支持。有一个扩展可以帮助你:github.com/sbrannen/spring-test-junit5
-
你能检查你从哪个包导入
TestRestTemplate吗?org.springframework.boot.test.web.client或org.springframework.boot.test? -
@harshavmb 我使用的是 org.springframework.boot.test.web.client 而不是已弃用的。
-
@LucasP 我会使用 JUnit 5 是的。我将尝试使用 JUnit 4 以确保问题不是来自 JUnit 版本。
-
@Lucas 我通过使用您提到的依赖项解决了我的问题。谢谢!问题是,在执行“mvn clean install”时,我的测试不是由 maven 运行的