简体   繁体   中英

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

I have a JUnit test that I would like to run against a REST service which is already running on my machine at the specified port. Already tested the REST service with Postman and it works fine.

The plan here is to make the REST URLs configurable by externalizing them in a properties file. Hence I tried following and the JUnit class is not able to read the properties file value.

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

First, you need to create an application context configuration for the test

@SpringBootApplication
@PropertySource(value = "classpath:application.properties")
public class TestContextConfiguration {

}

Second, let your test class use this configuration

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM