1

By default in a unit test class annotated with @SpringBootTest, a properties file in /src/main/java/resources is ignored if one exists in /src/test/java/resources.

How do you construct a test that loads values from both?

For example, this test will pass:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
class PortTests {

  @Test
  void testDefaultPort(@LocalServerPort int port) {
    assertThat(port).isEqualTo(12345);
  }

}

If the following file exists:

/src/main/java/resources/application.yaml

server:
  port: 12345

But that same test fails if you add the following file as well:

/src/test/java/resources/application.yaml:

foo: bar

How do you construct a test that passes when both files exist?

peterl
  • 1,881
  • 4
  • 21
  • 34
  • Does [Load different application.yml in SpringBoot Test](https://stackoverflow.com/questions/38711871/load-different-application-yml-in-springboot-test) answer your question? – Idan Elhalwani May 28 '22 at 06:31
  • Why would you simply not copy over all needed resources to test/java/resources? src and test resources and/or data should be decoupled as a fundamental rule. – Tintin May 28 '22 at 06:36
  • If you want both, add a application-test.yml in your test, and active that profile: "test". It will load both the application.yml in main and application-test.yml in test. – SeanH May 28 '22 at 08:35

1 Answers1

1

You should have separate resources for each environment, the test has its own folder structure and should has its own different properties

/src/main/java/resources

/src/test/java/resources

Just try to copy all the properties to the test resource file and change the values based on your configuration.

Hany Sakr
  • 2,591
  • 28
  • 27