I have this behaviour in a spring test that I don't witness running the application.
My test class fail to load OpenElevationClientImpl bean even though the OpenElevationClient interface is mentionned in the annotation @SpringBootTest(classes = {OpenElevationClient.class}).
The purpose of this post is that I cannot explain that the OpenElevationClientImpl bean is correctly loaded if I reference in @SpringBootTest annotation a class with the @ComponentScan annotation from the same package of the OpenElevationClient interface.
The test class
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = {RestClientConfig.class, OpenElevationConfig.class})
public class EnrichmentUtilsTest {
@Autowired
ApplicationContext applicationContext;
@Autowired
OpenElevationClient elevationClient;
@Test
public void printBeans() {
for(String tmp:Arrays.asList(applicationContext.getBeanDefinitionNames())){
System.out.println(tmp);
}
}
}
All the following classes are from the same package.
OpenElevationClient interface: bean is not found if this class is in @SpringbootTest
@ComponentScan
public interface OpenElevationClient {
LocationElevationResultsDTO getElevation(String locations);
}
OpenElevationConfig class: bean is found if this class is in @SpringbootTest
@ComponentScan
public class OpenElevationConfig {
}
OpenElevationClientImpl bean
@Service
public class OpenElevationClientImpl implements OpenElevationClient {
private OpenElevationLookupApi openElevationLookupApi;
@Autowired
public OpenElevationClientImpl(OpenElevationLookupApi openElevationLookupApi, @Value("${openelevation.api.url}") String basePath) {
openElevationLookupApi.getApiClient().setBasePath(basePath);
this.openElevationLookupApi = openElevationLookupApi;
}
@Override
public LocationElevationResultsDTO getElevation(String locations) {
return this.openElevationLookupApi.getLookup(locations);
}
}
Again, this behaviour is only witnessed running the tests and the OpenElevationConfig.class is only used as a component class to use for loading the ApplicationContext in the test class. Anything I missed that could explained this strange behaviour to me?
EDIT 16/12/2021 - repo to reproduce https://github.com/charlycou/stackoverflow-70198445.
- Replace OpenElevationConfig.class with OpenElevationClient.class in the test (AppTest) and the test will fail.
- Remove OpenElevationConfig.class and run Main.class and the application is running fine