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

标签 java spring rest spring-boot junit

我有一个 JUnit 测试,我想针对 REST 服务运行该测试,该服务已经在我的机器上的指定端口上运行。已经使用 Postman 测试了 REST 服务,它工作正常。

这里的计划是通过将它们外部化到属性文件中来使 REST URL 可配置。因此,我尝试了以下操作,但 JUnit 类无法读取属性文件值。

StoreClientTest.java

@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;
    }

}

src\test\main\resources\application.properties

name=abc

最佳答案

首先,您需要为测试创建一个应用上下文配置

@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 ..
}  

关于java - 无法从 JUnit 中的 Spring Boot 读取应用程序属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42121291/

相关文章:

java - 如何将 Java 安全层(Apache Shiro|Spring Security)集成到 webapp 菜单系统

java - 比较Java中的两个整数数组

spring - ElasticsearchTemplate.scroll 是否返回新的 scrollId?

mysql - 如何在 strongloop 中使用 MySql 存储过程创建 Web 服务

java - 如何在Java中为JRadiobuttons分配数值并将其用作乘数?

java - 冗余条件

Spring Boot 完整 REST CRUD 示例

java - Spring Boot 中的 Junit Test 不注入(inject)服务

java - PUT方法(RESTful)不能用作更新资源的方法

android - 多个 httpPost 到遥远的 Restful 服务 (JSON)