Close

Spring Testing - @TestPropertySource Example

[Last Updated: Jul 17, 2017]

This example demonstrates how to use @TestPropertySource. It is a class-level annotation that is used to specify which properties files should be loaded when running the test class.

Test property sources have the highest precedence than all other properties sources. That means Test source will override all other properties.

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.properties

report-subscriber=theManager@example.com

src/main/resources/test.properties

report-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:

Output

theManager@example.com

The JUnit test

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = AppConfig.class)
@TestPropertySource("classpath:test.properties")
public class ReportServiceTests {
  @Autowired
  private ReportService reportService;

  @Test
  public void testReportSubscriber() {
      String s = reportService.getReportSubscriber();
      System.out.println(s);
      Assert.assertEquals("theDeveloper@example.com", s);
  }
}
mvn  -q test -Dtest=ReportServiceTests

Output

d:\example-projects\spring-core-testing\test-property-source-annotation>mvn  -q test -Dtest=ReportServiceTests

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.ReportServiceTests
theDeveloper@example.com
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.391 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

Example Project

Dependencies 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

Spring Test Property Source Example Select All Download
  • test-property-source-annotation
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • resources
      • test
        • java
          • com
            • logicbig
              • example
                • ReportServiceTests.java

    See Also