【问题标题】:Not able to read application properties from Spring Boot in JUnit?无法从 JUnit 中的 Spring Boot 读取应用程序属性?
【发布时间】:2017-06-26 13:16:32
【问题描述】:

我有一个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

【问题讨论】:

  • 你有没有尝试改变src\test\resources\application.properties中的包?
  • 不确定您所说的“更改包”是什么意思。你能详细说明一下吗?

标签: java spring rest spring-boot junit


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-03
    • 2021-12-07
    • 2021-09-01
    • 2017-06-17
    • 1970-01-01
    • 2014-01-07
    • 1970-01-01
    • 2021-03-22
    相关资源
    最近更新 更多