У меня есть приложение с 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;
Как видите, в классе есть много аннотаций @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>
В папке тест / ресурсы у меня есть файл 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));
}
}
Но тест выдает исключение NullPointerException, когда пытается использовать foodRequiresBox, поэтому есть проблема с чтением файла application.properties.
Подскажите, как мне прочитать файл application.properties для тестов?




1-е решение
Я бы рекомендовал использовать внутреннюю аннотацию Spring под названием @SpringJUnitConfig.
Эта аннотация фактически такая же, как и @ExtendWith(SpringExtension.class)НО, вы можете настроить контексты приложения Spring для своего теста так же, как вы использовали @ContextConfiguration.
Или, если вам нужен полный Spring Boot Test, вы можете просто объединить:
@SpringJUnitConfig
@SpringBootTest
public class OrderServiceTest {
...
}
2-е решение
Другой способ - вообще не использовать Spring, а издеваться над всеми внутренними вещами, например, Mockito и напишите простой простой модульный тест.
Затем вы можете установить свои обычные через Spring аннотированные поля @Value через org.springframework.test.util.ReflectionTestUtils.
Я бы предпочел второе решение первому для меньших накладных расходов на инициализацию контекста Spring
вам нужно запустить контекст Spring в вашем тесте, если вам нужны значения из файла свойств. Если вы не хотите запускать контекст, вам следует использовать mockito и
.when