Reputation: 5374
I am trying to access application.properties or application-test.properties from within JUnit inside my Spring Boot application.
I keep seeing different ways to do this on Stack Overflow and only wish to use my AppConfig class (see below).
Am using Spring Boot 1.5.6 RELEASE and Java 1.8
Here's the structure to my application:
MyService
pom.xml
src
├───main
│ ├───java
│ │ └───com
│ │ └───myservice
│ │ ├───config
│ │ │ AppConfig.java
│ │ └───controller
│ │ │ UserController.java
│ │ │
│ │ └─── MyServiceApplication.java
│ ├───resources
│ │ application.properties
└───test
├───java
│ └───com
│ └───myservice
│ └───controller
│ UserControllerTest.java
└───resources
application-test.properties
com.myservice.config.AppConfig:
@Configuration
public class AppConfig {
@Value("${userDir}")
private String userDir;
// Getters & setters omitted for brevity
}
main/resources/application.properties:
server.contextPath=/MyService
server.port=8080
# users dir
userDir=/opt/users
test.resources/application-test.properties
# users dir
userDir=/opt/users
Am able to obtain & parse this dir within my main Spring Boot application, but I get a NullPointerException when I tried to get it from within my JUnit test class getAllUsers() test method:
@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class)
@ActiveProfiles("test")
public class UserControllerTest {
@Autowired
MockMvc mvc;
@MockBean
AppConfig config;
@MockBean
UserService userService;
@Test
public void getAllUsers() throws Exception {
User users = new User(config.getUserDir());
// more lines of code
}
}
On Stack Overflow there are multiple ways to do this which I read as:
this.class.getClassLoader.getResourceAsStream(...)
// Wish to use my AppConfig.classQuestion(s):
What am I possibly doing wrong, should it just read from the application.properties file or from the test-properties.file?
How does one configure the @ActiveProfiles("test"), am I supposed to set this inside the Maven pom.xml somewhere?
Do I need to place AppConfig inside a source folder under test/java/com/myservice/config?
Upvotes: 8
Views: 24785
Reputation: 497
You can use @TestPropertySource annotation in your test class.
Just annotate
@TestPropertySource("classpath:config/testing.properties")
on your test class.You should be able to read out the property for example with the @Value annotation.
@Value("${fromTest}")
private String fromTest;
your config like this
src/main/resources/config/testing.properties
Upvotes: 2
Reputation: 1914
Add the following annotation to your test class:
@TestPropertySource(locations="classpath:application-test.properties")
this should get you working :) please note that you have to import it:
import org.springframework.test.context.TestPropertySource;
Upvotes: 1