无法从JUnit中的Spring Boot读取应用程序属性?

时间:2017-02-08 18:49:58

标签: java spring rest spring-boot junit

我有一个JUnit测试,我希望针对已在指定端口的计算机上运行的REST服务运行。已经使用RESTPostman服务进行了测试,效果很好。

此处的计划是通过在属性文件中将REST URL外部化,使JUnit URL可配置。因此我尝试了以下操作,@RunWith(SpringJUnit4ClassRunner.class) @PropertySource("classpath:application.properties") public class StoreClientTest { private static final String STORE_URI = "http://localhost:8084/hpdas/store"; private RestTemplate restTemplate; @Value("${name}") private String name; @Before public void setUp() { restTemplate = new RestTemplate(); } @Test public void testStore_NotNull() { //PRINTS ${name} instead of abc ????? System.out.println("name = " + name); assertNotNull(restTemplate.getForObject(STORE_URI, Map.class)); } @After public void tearDown() { restTemplate = null; } } 类无法读取属性文件值。

StoreClientTest.java

name=abc

SRC \测试\主\资源\ application.properties

hybrid flow

1 个答案:

答案 0 :(得分:3)

首先,您需要为测试

创建应用程序上下文配置
@SpringBootApplication
@PropertySource(value = "classpath:application.properties")
public class TestContextConfiguration {

}

其次,让您的测试类使用此配置

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = TestContextConfiguration.class)
public class StoreClientTest {

    @Value("${name}")
    private String name;
    // test cases ..
}  
相关问题