Richard H.M
Richard H.M

Reputation: 406

Spring boot unit test how to load files

everyone。When I was writing junit, I found that @ActiveProfiles corresponds to my resource directory。 I don’t understand how spring boot loads resource files,And why if I don’t specify @ActiveProfiles which application file is read by default?

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@SpringBootTest(classes = Application.class)
@ActiveProfiles("test")
public class NewTutorGroupIaoTest {
}
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@SpringBootTest(classes = Application.class)
@ActiveProfiles("test")
public class NewTutorGroupIaoTest {
}

project directory:

project 
- src 
    - main
        - java
        - resource
    - test
        - java
        - resource

Upvotes: 0

Views: 312

Answers (1)

Rob Evans
Rob Evans

Reputation: 2874

If you mark classes with @Profile("test"), you can ensure they're loaded (into the ApplicationContext) by activating the test profile - either with @ActiveProfiles("test"), spring.profiles.active=test, or a number of other ways. Classes can be excluded with @Profile("!test")

More details here: https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-profiles

Also, by activating a profile, you may also activate a properties file to be picked up... You may also have files in your project like:

  • application.properties
  • application-default.properties
  • application-test.properties

If you have application.properties present as well as application-test.properties, application.properties forms the base config, and application-test.properties will overwrite any existing properties and may also supply additional configuration values.

If you supply/specify no profile, the default profile is activated. This will result in application.properties + application-default.properties being combined (as before).

You will see in the logs which profile is activated very near the beginning of the Spring log output.

Upvotes: 1

Related Questions