Spring Boot tests: How to override the properties in your test class


Override properties defined in .properties in your test class

In this example we have a simple configuration class:

import org.springframework.beans.factory.annotation.Value; 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.Configuration; 
public class ExampleConfiguration { 
    private String valueName; 
    public String doSomethingWithTheValue() { 
        return valueName; 

In this simple example we define a @Bean that uses the property example.value.name. Spring searches this value in an application.properties file at the moment of the build and it replaces the references of valueName with the value in the file.

Override a property value in a test class

In a Spring Boot test class we could reference an application.properties file with our test values. But sometimes we need to test multiple properties or we prefer to manage them directly in the test class.

In this case we can override the property directly in the test class, example:

import ... 
@SpringBootTest(classes = ExampleConfiguration.class) 
@TestPropertySource(properties = {"example.value.name=myTest"}) 
class ExampleConfigurationTest { 
 ExampleConfiguration exampleConfiguration; 
 void testValue() { 
     assertEquals("myTest", exampleConfiguration.doSomethingWithTheValue()); 

We need to declare the test with @SpringBootTest to tell Spring that it has to handle this code, but we don't want to load the complete application.

For this reason tell to Spring that we want to test only ExampleConfiguration.class.

To override the properties we can use @TestPropertySource, this annotation allows us to override existing properties or to load alternative properties files:


Fullstack Angular / Java application quick start guide.
WebApp built by Marco using SpringBoot 3.2.4 and Java 21. Hosted in Switzerland (GE8).