Spring boot SpringBoot 2+;Junit5:带@Value的null

Spring boot SpringBoot 2+;Junit5:带@Value的null,spring-boot,junit,junit5,spring-boot-test,Spring Boot,Junit,Junit5,Spring Boot Test,我有一个使用SpringBoot2和Junit5的应用程序,现在我正在尝试进行测试。我有一个名为OrderService的类,它如下所示: @Component public class OrderService { @Value("#{'${food.requires.box}'.split(',')}") private List<String> foodRequiresBox; @Value("#{'${properties.prioritization}'.split(',

我有一个使用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;
@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));
    }
}
测试文件如下所示:

@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;
@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文件吗?

1st Solution

我建议使用Spring的内部注释
@SpringJUnitConfig
此注释实际上与
@ExtendWith(SpringExtension.class)
相同,但是您可以使用与使用
@ContextConfiguration
相同的方式为测试配置spring应用程序上下文

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

@SpringJUnitConfig
@SpringBootTest
public class OrderServiceTest {
...
}
第二种解决方案

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

通过Spring注入注释的
@Value
字段设置正常值。如果需要属性文件中的值,您需要在测试中运行Spring上下文。如果你不想启动上下文,你应该使用mockito和
。当
我宁愿使用第二种解决方案而不是第一种解决方案,这样可以减少初始化spring上下文的开销