【问题标题】:Value annotation not working in Junit test值注释在 Junit 测试中不起作用
【发布时间】:2019-02-17 00:00:40
【问题描述】:
@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 文件中获取一个字符串,并在我的 Junit 测试的一个字段中插入 @Value。我以前在普通课堂上做过这个,但我在测试中的字段上为空。我阅读了有关此问题的类似问题,并且到目前为止尝试创建 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)

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

【问题讨论】:

  • 你可以试试this
  • 请添加您的测试...仅添加一些 sn-ps 是行不通的。
  • @M.Deinum 确实 :))我添加了我的测试现在的样子
  • 你至少需要一个@RunWith(SpringRunner.class)来测试方法。 @SpringBootTest 现在几乎没用了。
  • @M.Deinum 这只是我尝试的最新方法......使用 RunWith(SpringRunner.class) 我得到 java.net.URISyntaxException: Illegal character in path at index 1: ${myUrl} /v2/rules 我不确定为什么 Uri 会这样开始

标签: java spring junit


【解决方案1】:

以下对我有用。它从 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 docs

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

【讨论】:

    【解决方案2】:

    尝试在您的测试类中使用@TestPropertySource

    【讨论】:

    • 我试图@TestPropertySource("application.properties"),但无法弄清楚如何导入注释。它允许我@PropertySource,但不能使用TestPropertySource
    • 嗯你的意思是你不能导入注释??检查你是否有这个包docs.spring.io/spring-framework/docs/current/javadoc-api/org/…
    • 当我对字符串进行硬编码时,它可以工作,但是使用这个注释和值我得到 org.apache.http.client.ClientProtocolException org.apache.http.ProtocolException: Target host is not specified
    【解决方案3】:

    请使用下面的方式获取Junit中变量的值

    ReflectionTestUtils.setField(YOURCONTROLLER, "variableName", valueOfString);
    

    变量为布尔值时的示例。变量名称也应与控制器中的名称相同。

    ReflectionTestUtils.setField(myController, "isFlag", true);
    

    你还需要添加 pom 依赖

    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>3.2.0.RELEASE</version>
    <type>jar</type>
    <scope>test</scope>
    </dependency>
    

    【讨论】:

    • 我什至尝试使用更新版本的 spring-test 5.0.9.RELEASE 并且我试图从 application.properties 文件中获取变量 String ,而不是从控制器中获取,它是相同的名称
    • 你的意思是变量 String 只用在测试用例中而不是在任何控制器中?
    • 我在 application.properties 中有这个字符串变量,我只在测试中使用它,所以如果需要,我可以从 application.properties 文件中更改地址,这就是为什么我想尽量避免硬编码每次测试,因为如果有人想更改地址,他必须在每个地方都这样做
    • 你试过@TestPropertySource("/application-test.properties")注解吗?
    • 是的,我试过了,现在我再次检查了它,但结果相同
    【解决方案4】:

    你需要添加

    @PropertySource("classpath:test.properties")
    

    例如:

    @Configuration
    @ComponentScan(basePackages = { "com.app.*" })
    @PropertySource("classpath:test.properties")
    public class MyAppConfig {
    ///
    }
    

    如果您需要不同的配置进行测试或覆盖 application.properties 中的值

    @TestPropertySource(locations="classpath:test.properties")
    

    例如:

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringApplicationConfiguration(classes = MyApplication.class)
    @TestPropertySource(locations="classpath:test.properties")
    public class MyApplicationTests {
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-23
      • 1970-01-01
      • 1970-01-01
      • 2012-09-28
      • 1970-01-01
      • 1970-01-01
      • 2011-02-10
      相关资源
      最近更新 更多