gpt4 book ai didi

spring-boot - Spring 启动 2 + Junit 5 : null with @Value

转载 作者:行者123 更新时间:2023-12-05 03:04:29 24 4
gpt4 key购买 nike

我有一个使用 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 的内部注解 @SpringJUnitConfig此注解实际上与 @ExtendWith(SpringExtension.class) 相同 但是 您可以按照与使用 相同的方式为您的测试配置 spring 应用程序上下文@ContextConfiguration.

或者如果你想要一个完整的 Spring Boot 测试,你可以结合:

@SpringJUnitConfig
@SpringBootTest
public class OrderServiceTest {
...
}

第二个解决方案

另一种方法是根本不使用 Spring,而是使用例如模拟所有内部的东西。 Mockito 并编写一个简单的单元测试。然后,您可以通过 org.springframework.test.util.ReflectionTestUtils 通过 Spring 注入(inject)注释的 @Value 字段来设置您的正常设置。

关于spring-boot - Spring 启动 2 + Junit 5 : null with @Value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52919296/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com