6

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.

luboskrnac
  • 23,973
  • 10
  • 81
  • 92
Héctor
  • 24,444
  • 35
  • 132
  • 243

2 Answers2

14

Use it this way:

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

and place test properties file into src/test/resources

Héctor
  • 24,444
  • 35
  • 132
  • 243
luboskrnac
  • 23,973
  • 10
  • 81
  • 92
  • 1
    I tested, my case it works with: @TestPropertySource(locations = "file:./src/test/resources/application.properties") – Stefano Apr 02 '20 at 19:07
0

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.

phirzel
  • 139
  • 2
  • 5
  • Did not work for me, the second file does not override properties of the first... – Migs Sep 04 '19 at 09:52
  • Repeating an annotation does not `overwrite` or override - it `adds`. – Anly Jan 19 '20 at 13:22
  • Actually worked for me. I have a module client which is used by other modules then in my module custom-client-test I added override.properties file which really overrides props from mydefault.properties in client module (of course override.properties doesn't exist in client module) – amisiuryk Jul 20 '20 at 09:24