Ale*_*her 4 junit spring-boot junit5 spring-boot-test
我有一个带有 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;
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,该类有许多 @Value 注释,用于从 application.properties 文件中提取值。
在 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>
Run Code Online (Sandbox Code Playgroud)
在test/resources文件夹中,我有包含以下信息的 application.properties 文件:
properties.prioritization:vip,food
food.requires.box:pizza,cake,flamingo
further.distance:2
slot.meters.long:0.5
Run Code Online (Sandbox Code Playgroud)
测试文件如下所示:
properties.prioritization:vip,food
food.requires.box:pizza,cake,flamingo
further.distance:2
slot.meters.long:0.5
Run Code Online (Sandbox Code Playgroud)
但测试在尝试使用foodRequiresBox时会抛出 NullPointerException ,因此读取 application.properties 文件时出现问题。
你能告诉我如何读取 application.properties 文件进行测试吗?
第一个解决方案
我建议使用 Spring 的内部注释,称为@SpringJUnitConfig
此注释实际上与相同@ExtendWith(SpringExtension.class) ,但您可以按照与过去使用相同的方式为测试配置 Spring 应用程序上下文@ContextConfiguration。
或者,如果您想要完整的 Spring Boot 测试,您可以组合:
@SpringJUnitConfig
@SpringBootTest
public class OrderServiceTest {
...
}
Run Code Online (Sandbox Code Playgroud)
第二种解决方案
另一种方法是根本不使用 Spring,而是使用 Mockito 等模拟所有内部内容并编写一个简单的单元测试。@Value然后,您可以通过 Spring 注入注释字段来正常设置org.springframework.test.util.ReflectionTestUtils。
| 归档时间: |
|
| 查看次数: |
8632 次 |
| 最近记录: |