Search code examples
javaspringspring-bootspring-testjunit-jupiter

@ContextConfiguration in test if parent has @ContextHierarchy


I have tests for class, that uses RestTemplate. Now I need to write another test for the similar class. I've decided to move @ContextHierarchy to separate interface like below

@ContextHierarchy({
        @ContextConfiguration(classes = {
                ObjectMapperConfiguration.class, // ObjectMapper
                HttpMessageConverterConfiguration.class // MappingJackson2HttpMessageConverter
        }),
        @ContextConfiguration(classes = HttpMessageConvertersAutoConfiguration.class),
        @ContextConfiguration(classes = RestTemplateAutoConfiguration.class), // RestTemplate builder
        @ContextConfiguration(classes = {
                RestTemplateConfig.class, // finally RestTemplate
                // tested service was HERE
        })
})
public interface RestTemplateTest {
}

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = TestedService.class) // now it is HERE
public class RestTest implements RestTemplateTest {
}

The problem is that code about doesn't work. I receive error message from Spring that TestedService cannot be created because there's no bean of type RestTemplate.

If I move TestedService back to @ContextHierarchy then everything is fine.


Solution

  • It's turned out that to make everything to work RestTemplateTest must be a class, not an interface