【发布时间】:2019-03-25 22:26:57
【问题描述】:
我有一个带有 SpringBoot2 和 Junit5 的应用程序,现在我正在尝试进行测试。我有一个名为 OrderService 的类,它看起来像这样:
@Component
public class OrderService {
@Value("#{'${food.requires.box}'.split(',')}")
private List<String> foodRequiresBox;
@Value("#{'${properties.prioritization}'.split(',')}")
private List<String> prioritizationProperties;
@Value("${further.distance}")
private Integer slotMeterRange;
@Value("${slot.meters.long}")
private Double slotMetersLong;
如您所见,该类有许多从 application.properties 文件中提取值的 @Value 注释。
在 POM 文件中我有这些依赖:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.1.0</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<version>2.0.5.RELEASE</version>
</dependency>
在 test/resources 文件夹中,我有包含以下信息的 application.properties 文件:
properties.prioritization:vip,food
food.requires.box:pizza,cake,flamingo
further.distance:2
slot.meters.long:0.5
测试文件如下所示:
@ExtendWith(SpringExtension.class)
@TestPropertySource(locations="classpath:application.properties")
public class OrderServiceTest {
OrderService orderService;
@BeforeEach
void before(){
orderService = new OrderService();
}
@Test
void findAll() {
Order order = new Order().withDescription("2x Pizza with Salad\\n2x Kebab with Fries\\n1x Hot dog with Fries\\n2x Pizza with Fries");
assertTrue(orderService.orderHasFood.test(order));
}
}
但是测试在尝试使用foodRequiresBox时抛出NullPointerException,所以读取application.properties文件有问题。
您能告诉我如何读取用于测试的 application.properties 文件吗?
【问题讨论】:
-
如果您需要属性文件中的值,您需要在测试中运行 spring 上下文。如果你不想启动上下文,你应该使用 mockito 和
.when
标签: spring-boot junit junit5 spring-boot-test