I have a main class that uses @ComponentScan
along with excludeFilters
to exclude a class that is used from a library.
@Configuration
@ComponentScan(basePackages = {"org.example"},
excludeFilters = {
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {
org.example.framework.exception.ExceptionConfig.class,
}),
})
@EnableAsync
@EnableCaching
@EnableAutoConfiguration
@EnableScheduling
public class Main {
public static void main(String[] args) {
ConfigurableApplicationContext appContext = SpringApplication.run(Main.class, args);
MyAppInitializer initializer = appContext.getBean(MyAppInitializer.class);
initializer.init(appContext);
}
}
With normal execution the beans defined in ExceptionConfig
are not initialized and I am able to write my own CustomExceptionConfig
class
While running tests the ExceptionConfig
is not excluded so the tests have different result than normal execution.
@ActiveProfiles("test")
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = Main.class, webEnvironment = WebEnvironment.DEFINED_PORT)
public class ApiTest {
.
.
.
}
I tried creating a separate test configuration like:
@Configuration
@ComponentScan(basePackages = {"org.example"},
excludeFilters = {
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {
org.example.framework.exception.ExceptionConfig.class,
}),
})
public class TestConfiguration {
}
And changing the ApiTest
class:
@SpringBootTest(classes = {Main.class, TestConfiguration.class} , webEnvironment = WebEnvironment.DEFINED_PORT)
Still the behaviour is same.
Defining a TypeExcludeFilter
and using that in configuration class did not help either.
@EqualsAndHashCode
public class TestExcludeFilter extends TypeExcludeFilter {
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
return metadataReader.getClassMetadata().getClassName().equals("org.example.framework.exception.ExceptionConfig.class");
}
}