Spring Testing - @TestPropertySource default properties file detection [Updated: Jul 18, 2017, Created: Jul 17, 2017] |
|
||
This example demonstrates how to use an implicit properties location for @TestPropertySource. If @TestPropertySource is declared as an empty annotation (i.e., without explicit values for the locations or properties attributes), an attempt will be made to detect a default properties file (on the classpath) relative to the class that declares the annotation. ExampleCreating a Spring application@Service public class ReportService { @Value("${report-subscriber:admin@example.com}") private String theSubscriber; public String getReportSubscriber() { return theSubscriber; } } src/main/resources/prod.propertiesreport-subscriber=theManager@example.com src/main/resources/test.propertiesreport-subscriber=theDeveloper@example.com @PropertySource("classpath:prod.properties") @Configuration @ComponentScan public class AppConfig { @Bean public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() { return new PropertySourcesPlaceholderConfigurer(); } public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); ReportService rs = context.getBean(ReportService.class); System.out.println(rs.getReportSubscriber()); } } Running above class: OutputtheManager@example.com The default properties filesrc/test/resources/com/logicbig/example/ReportServiceTests.propertiesreport-subscriber=theTester@example.com The JUnit testWe are not going to specify 'locations' or 'properties' attribute with @TestPropertySource: @RunWith(SpringRunner.class) @ContextConfiguration(classes = AppConfig.class) @TestPropertySource public class ReportServiceTests { @Autowired private ReportService reportService; @Test public void testReportSubscriber() { String s = reportService.getReportSubscriber(); System.out.println(s); Assert.assertEquals("theTester@example.com", s); } } mvn -q test -Dtest=ReportServiceTests OutputD:\example-projects\spring-core-testing\test-property-source-with-default-location>mvn -q test -Dtest=ReportServiceTests Example ProjectDependencies and Technologies Used:
|
|
||
|
|||
|