AntonBoarf
AntonBoarf

Reputation: 1313

Spring Test : why cannot access application.properties?

I'm building an extremly easy Spring Boot application. It has no code, just a simple test :

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTest {

    @Value("${my.key}")
    private String key;

    @Test
    public void test() {
        System.out.println(key);
    }
}

my.key is defined inside src/main/resources/application.properties (in main/ not test/)

The test doesn't pass because cannot find my.key property (but if I put this property inside src/test/resources/application.properties it works)

I'm sure I have seen plenty of Spring Boot applications where test classes read properties from /main/resources/application.properties

But here it does not work.

Upvotes: 4

Views: 6633

Answers (2)

rieckpil
rieckpil

Reputation: 12021

If you also add a application.properties file inside src/test/resources, this will "override" the one in src/main/resources, and hence none of the keys you define in your "production" properties file will be seen.

So either remove your application.properties in src/test/resources to use your property file in src/main/resources or define your values there.

Upvotes: 6

user3776401
user3776401

Reputation: 29

You can use @TestPropertySource to override the location of your application.properties.

@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(locations="classpath:application.properties")
public class MyTest {

}

For further help on how to use it, please check here

Upvotes: 1

Related Questions