1

I try to create a simple custom spring boot starter that read property in application.properties :

@EnableConfigurationProperties({ CustomStarterProperties.class })
@Configuration
public class CustomStarterAutoConfiguration {

    @Autowired
    private CustomStarterProperties properties;

    @Bean
    public String customStarterMessage() {
        return properties.getMessage();
    }
}

with its ConfigurationProperties :

@ConfigurationProperties(prefix = "custom.starter")
public class CustomStarterProperties {

    private String message;

  /* getter and setter */
           ...
}

There is also the corresponding application.properties and META-INF/spring.factories to enable the autoconfiguration.

I have another project that declares this starter as a dependency and in which I write a test to see if the customStarterMessage Bean is created :

@RunWith(SpringRunner.class)
@EnableAutoConfiguration
public class TotoTest {

    @Autowired
    String customStarterMessage;

    @Test
    public void loadContext() {
        assertThat(customStarterMessage).isNotNull();
    }
}

This test fails (even with the appropriate application.properties file in the project) because the application.properties seems to not be read.

It works well with a @SpringBootTest annotation instead of the @EnableAutoConfiguration but I would like to understand why EnableAutoConfiguration is not using my application.properties file whereas from my understanding all the Spring AutoConfiguration are based on properties.

Thanks

Jainil
  • 1,488
  • 1
  • 21
  • 26
matdan
  • 13
  • 5
  • are you using different package names? If the dependency that you are including has a different package, you'll need to also add a `@ComponentScan` for the package from the dependency, besides the package that you have in your second project. – Andrei Sfat Oct 30 '19 at 13:53
  • Thanks @AndreiSfat ! I have tried a `@ComponentScan` with the right package declaration but it did not work :( – matdan Oct 30 '19 at 14:01

1 Answers1

0

@EnableAutoConfiguration on test classes don't prepare required test context for you.

Whereas @SpringBootTest does default test context setup for you based on default specification like scanning from root package, loading from default resources. To load from custom packages which are not part of root package hierarchy, loading from custom resource directories you have define that even in test context configuration. All your configurations will be automatically done in your actual starter project based on @EnableAutoConfiguration you defined.

ScanQR
  • 3,740
  • 1
  • 13
  • 30
  • Thank you @ScanQR !! I made it work by adding `@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class)` on my test class. – matdan Oct 30 '19 at 14:29
  • @matdan sure. If you find answer useful then do accept it. Thanks! – ScanQR Oct 30 '19 at 14:30