簡體   English   中英

無法從 JUnit 中的 Spring Boot 讀取應用程序屬性?

[英]Not able to read application properties from Spring Boot in JUnit?

我有一個JUnit測試,我想針對REST服務運行該測試,該服務已在我的機器上的指定端口上運行。 已經用Postman測試了REST服務,它工作正常。

這里的計划是通過在屬性文件中將REST URL 外部化來使它們可配置。 因此,我嘗試了以下操作,但JUnit類無法讀取屬性文件值。

商店客戶端測試.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 ..
}  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM