Héctor
Héctor

Reputation: 26034

Override @PropertySource with @TestPropertySource in Spring Boot

I have my Spring Boot main class:

@SpringBootApplication
@PropertySource("file:/my/file/properties")
public class Application extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(Application.class);
    }
  //main method
}

I'm reading properties from an external file (using @PropertySource). Now, I have an integration test:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes= Application.class)
@WebIntegrationTest
@TestPropertySource("file:/my/test/file/properties") // <---
public class MyTest {
  //some tests
}

I need to use another external properties file, different from the indicated in @PropertySource in Application class. For that reason, I have added @TestPropertySource, but seems that this annotation is not overriding the @PropertySource.

What can I do?

Thanks in advance.

Upvotes: 7

Views: 13537

Answers (2)

phirzel
phirzel

Reputation: 137

In Java8 you can "repeat" an Annotation like:

@PropertySource(value = "file:./src/main/resources/mydefault.properties")
@PropertySource(value = "file:./src/test/resources/override.properties", ignoreResourceNotFound = true)

This way, the latter overwrites properties from the first file if available.

Upvotes: 0

luboskrnac
luboskrnac

Reputation: 24561

Use it this way:

@TestPropertySource(locations = "classpath:test.properties")

and place test properties file into src/test/resources

Upvotes: 16

Related Questions