Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value annotation not working in Junit test

Tags:

java

junit

spring

@SpringBootTest
public class RuleControllerTest {

@Value("${myUrl}")
private String myUrl;
private HttpClient httpClient = HttpClients.createDefault();

@Test
public void loadAllRules() throws IOException, URISyntaxException {
    String target = myUrl + "/v2/rules";
    String json = generateHTTPget(target);

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    Rule[] rules = objectMapper.readValue(json, Rule[].class);

    boolean correctResponse = rules != null ? true : false;
    int httpCode = getHTTPcode(target);
    boolean correctStatus = httpCode >= 200 && httpCode <= 300 ? true : false;

    assertTrue(correctStatus);
    assertTrue(correctResponse);
}

I am trying to get a String from my application.properties file and insert @Value in a field in my Junit test. I have done this before in normal class, but I have null on my field in the test. I read similar questions about this problem and so far tried to create src/test/resources package and clone the application.properties there. Also tried to add the dependency

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
</dependency>

and add the annotation

@RunWith(SpringRunner.class)

I get a message No tests found with test runner Junit 5 and in Problems tab i have springboottest.jar cannot be read or is not a valid ZIP file

Also tried

@PropertySource("classpath:application.properties")

as class annotation but with same result

I did try as well to :

@RunWith(SpringJUnit4ClassRunner.class)

If i hardcode the String myUrl to "http://localhost:8090" the test works so the problem is in the @Value not working

like image 568
Georgi Michev Avatar asked Jan 02 '23 21:01

Georgi Michev


1 Answers

Following works for me. It picks up value from the application.properties file.

@RunWith(SpringRunner.class)
@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class)
public class ValueAnnotationTest {

    @Value("${myUrl}")
    private String myUrl;

    @Test
    public void test1() throws Exception {
    assertThat(myUrl).isEqualTo("http://test.com");
    }
}

From Spring Boot docs:

Using ConfigFileApplicationContextInitializer alone does not provide support for @Value("${…​}") injection. Its only job is to ensure that application.properties files are loaded into Spring’s Environment. For @Value support, you need to either additionally configure a PropertySourcesPlaceholderConfigurer or use @SpringBootTest, which auto-configures one for you.

like image 195
Ritesh Avatar answered Jan 04 '23 10:01

Ritesh