Spring Boot 2 + Junit 5:带@Value 的 null

SpringBoot 2 + Junit5: null with @Value

我有一个SpringBoot2和Junit5的应用程序,现在我正在尝试进行测试。我有一个名为 OrderService 的 class,它看起来像这样:

@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;

如您所见,class 有许多 @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>

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) 相同,但是 您可以按照与使用 @ContextConfiguration 相同的方式为您的测试配置 spring 应用程序上下文.

或者,如果您想要完整的 Spring 启动测试,您可以结合使用:

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

第二个解决方案

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

注入带注释的 @Value 字段