@TestPropertySource Annotation Example

When we do integration testing of our Spring Boot application, we sometimes need to make it load an alternative configuration. For example, we might need to run and test our application on a different port number, make it connect to a database as a different user or even make it connect to a different database. In these cases, we can use the @TestPropertySource. 

The @TestPropertySource annotation allows us to test our Spring Boot application with alternative configuration values. In this tutorial, you will learn how it works.

If you are interested in learning more about how to test Java applications, please check the following tutorials:

Load Properties From a Different File

We can use the @TestPropertySource annotation to make Spring Framework load application properties from a different properties file. To do that, annotate the Test class with @TestPropertySource annotation and use the locations property to indicate the location of the properties file to load.

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@TestPropertySource(locations = "/application-test.properties")
public class UsersControllerIntegrationTest {

 ...

}

This will make Spring Framework load application properties from the application-test.properties file, and from the application.properties file as well. But the properties loaded from a file that is defined in the @TestPropertySource annotation will have higher precedence.

Also, notice that the test class is annotated with @SpringBootTest annotation. This is a very important annotation and can help you test your Spring Boot application in different types of Web Environments.

Properties with the Highest Precedence

We can use @TestPropertySource annotation to specify a list of properties that will have the highest precedence. To do that we use the  “properties” attribute.

@TestPropertySource(locations = "/application-test.properties", properties = "server.port=8081")

The value we specify using the “properties“, will have higher precedence than the value of the same property loaded from application-test.properties file.

Video Lessons

I hope this tutorial was of some value to you. If you like video tutorials,  then have a look at my video course called “Testing Java with JUnit and Mockito“. This video course is for absolute beginners, and you do not need to have any prior knowledge of testing Java applications to enrol.

Make sure to explore the Testing Java Code page as well. There, you’ll gain access to a range of informative tutorials that will empower you to construct well-structured and efficient test cases.

Happy learning!