值注释在 Junit 测试中不起作用

Geo*_*hev 4 java junit spring

@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);
}
Run Code Online (Sandbox Code Playgroud)

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

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)

并添加注释

@RunWith(SpringRunner.class)
Run Code Online (Sandbox Code Playgroud)

我收到一条消息 No tests found with test runner Junit 5 and in Problems tab i have springboottest.jar cannot be read or is not a valid ZIP file

也试过

@PropertySource("classpath:application.properties")
Run Code Online (Sandbox Code Playgroud)

作为类注释但结果相同

我也尝试过:

@RunWith(SpringJUnit4ClassRunner.class)
Run Code Online (Sandbox Code Playgroud)

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

Rit*_*esh 6

以下对我有用。它从 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");
    }
}
Run Code Online (Sandbox Code Playgroud)

来自Spring Boot 文档

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