5
@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

Georgi Michev
  • 764
  • 5
  • 18
  • 37
  • You can give a try to [this](https://stackoverflow.com/questions/32633638/testpropertysource-and-propertysource-dont-work-for-junit) – m4gic Sep 12 '18 at 11:07
  • 1
    Please add your test... Just adding some snippets isn't going to work. – M. Deinum Sep 12 '18 at 11:58
  • @M.Deinum Indeed :)) I added how my test looks like right now – Georgi Michev Sep 12 '18 at 12:03
  • 1
    You need at least a `@RunWith(SpringRunner.class)` on the test method. The `@SpringBootTest` is pretty much useless now. – M. Deinum Sep 12 '18 at 12:15
  • @M.Deinum It was just the latest thing I tried ... With RunWith(SpringRunner.class) I get java.net.URISyntaxException: Illegal character in path at index 1: ${myUrl}/v2/rules I am not sure why the Uri starts like this – Georgi Michev Sep 12 '18 at 12:29
  • '@RunWith' annotation has been replaced by the more powerful '@ExtendWith' annotation – Jacques Koorts Aug 11 '22 at 13:48

4 Answers4

10

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.

Ritesh
  • 7,472
  • 2
  • 39
  • 43
3

Try to use @TestPropertySource on your test class.

Antoniossss
  • 31,590
  • 6
  • 57
  • 99
  • I was trying to @TestPropertySource("application.properties"), but cant figure out how to import the annotation.. It allows me to @PropertySource, but not TestPropertySource – Georgi Michev Sep 12 '18 at 11:20
  • 1
    umm you mean you cannot import annotation?? Check if you have this package https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/context/TestPropertySource.html – Antoniossss Sep 12 '18 at 11:22
  • When I hardcode the String it works but with this annotation and Value I get org.apache.http.client.ClientProtocolException org.apache.http.ProtocolException: Target host is not specified – Georgi Michev Sep 12 '18 at 11:36
1

Please use below to get the value of the variable in Junit

ReflectionTestUtils.setField(YOURCONTROLLER, "variableName", valueOfString);

Example in case if variable is boolean. Also variable name should be same what it is in controller.

ReflectionTestUtils.setField(myController, "isFlag", true);

Also you will need to add pom dependency

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.0.RELEASE</version>
<type>jar</type>
<scope>test</scope>
</dependency>
Rmahajan
  • 1,311
  • 1
  • 14
  • 23
  • I tried even with a newer version of spring-test 5.0.9.RELEASE and I am trying to get the variable String from the application.properties file , not from controllers and it is the same name – Georgi Michev Sep 12 '18 at 11:43
  • You mean that variable String is only used in test case not in any controller ? – Rmahajan Sep 12 '18 at 12:32
  • I have this String variable in application.properties and I am using it only in the tests so I can change the address if needed from application.properties file, thats why I want to try avoid hardcoding it in every test, since if someone wants to change the address he would have to do it in every place – Georgi Michev Sep 12 '18 at 12:35
  • Have you tried with `@TestPropertySource("/application-test.properties")` annotation ? – Rmahajan Sep 12 '18 at 12:40
  • Yes I tried and I double checked it now, but with same result – Georgi Michev Sep 12 '18 at 13:03
0

You need to add

@PropertySource("classpath:test.properties")

for example:

@Configuration
@ComponentScan(basePackages = { "com.app.*" })
@PropertySource("classpath:test.properties")
public class MyAppConfig {
///
}

If you need different configurations for test or to override values in application.properties

@TestPropertySource(locations="classpath:test.properties")

for example :

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MyApplication.class)
@TestPropertySource(locations="classpath:test.properties")
public class MyApplicationTests {

}