首页 > 解决方案 > 值注释在 Junit 测试中不起作用

问题描述

@SpringBootTest
public class RuleControllerTest {

@Value("${myUrl}")
private String myUrl;
private HttpClient httpClient = HttpClients.createDefault();

@Test
public void loadAllRules() throws IOException, URISyntaxException {
    String target = myUrl + "/v2/rules";
    String json = generateHTTPget(target);

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    Rule[] rules = objectMapper.readValue(json, Rule[].class);

    boolean correctResponse = rules != null ? true : false;
    int httpCode = getHTTPcode(target);
    boolean correctStatus = httpCode >= 200 && httpCode <= 300 ? true : false;

    assertTrue(correctStatus);
    assertTrue(correctResponse);
}

我正在尝试从我的 application.properties 文件中获取一个字符串,并将 @Value 插入到我的 Junit 测试的字段中。我以前在普通课上做过这个,但是我在测试中的字段上是空的。我阅读了有关此问题的类似问题,并且到目前为止尝试创建 src/test/resources 包并在那里克隆 application.properties。还尝试添加依赖项

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
</dependency>

并添加注释

@RunWith(SpringRunner.class)

我收到一条消息 No tests found with test runner Junit 5 并且在 Problems 选项卡中我有 springboottest.jar 无法读取或不是有效的 ZIP 文件

也试过

@PropertySource("classpath:application.properties")

作为类注释,但结果相同

我也尝试过:

@RunWith(SpringJUnit4ClassRunner.class)

如果我将 String myUrl 硬编码为“ http://localhost:8090 ”,则测试有效,因此问题出在 @Value 不起作用

标签: javaspringjunit

解决方案


以下对我有用。它从 application.properties 文件中获取值。

@RunWith(SpringRunner.class)
@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class)
public class ValueAnnotationTest {

    @Value("${myUrl}")
    private String myUrl;

    @Test
    public void test1() throws Exception {
    assertThat(myUrl).isEqualTo("http://test.com");
    }
}

来自Spring Boot 文档

单独使用ConfigFileApplicationContextInitializer不支持@Value("${…​}")注入。它唯一的工作是确保将 application.properties文件加载到 Spring 的环境中。为了获得 @Value支持,您需要另外配置 a PropertySourcesPlaceholderConfigurer或 use @SpringBootTest,它会为您自动配置一个。


推荐阅读