This example demonstrates how to use 'properties' attribute of @TestPropertySource to specify inlined properties. The inlined properties will override properties coming from the sources loaded via 'locations' attribute (if specified any).
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 JUnit test
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = AppConfig.class)
@TestPropertySource(locations = "classpath:test.properties",
properties = "report-subscriber=tester@example.com")
public class ReportServiceTests {
@Autowired
private ReportService reportService;
@Test
public void testReportSubscriber() {
String s = reportService.getReportSubscriber();
System.out.println(s);
Assert.assertEquals("tester@example.com", s);
}
} mvn -q test -Dtest=ReportServiceTests Outputd:\example-projects\spring-core-testing\test-property-source-with-inlined-properties>mvn -q test -Dtest=ReportServiceTests
------------------------------------------------------- T E S T S ------------------------------------------------------- Running com.logicbig.example.ReportServiceTests tester@example.com Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.399 sec
Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
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
|