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:
- That JUnit classes can read application.properties from main/resources/application.properties.
- Using
this.class.getClassLoader.getResourceAsStream(...)
// Wish to use my AppConfig.class
Question(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?