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.
Example
Creating 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 file
src/test/resources/com/logicbig/example/ReportServiceTests.propertiesreport-subscriber=theTester@example.com
The JUnit test
We 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
------------------------------------------------------- T E S T S ------------------------------------------------------- Running com.logicbig.example.ReportServiceTests theTester@example.com Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.41 sec
Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
INFO: Detected default properties file "classpath:com/logicbig/example/ReportServiceTests.properties" for test class [com.logicbig.example.ReportServiceTests]
Example ProjectDependencies and Technologies Used: - spring-context 4.3.8.RELEASE: Spring Context.
- spring-test 4.3.9.RELEASE: Spring TestContext Framework.
- junit 4.12: JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.
- JDK 1.8
- Maven 3.3.9
|