Excluding classes from the test context

How to exclude some of the beans from loading using a scan component in a context that is <import> from another xml that requires scanning of all packages. This works well if I put it in the main context:

 <context:component-scan base-package="com.main"> <context:exclude-filter expression="com.main.*Controller" type="regex"/> </context:component-scan> 

But I need controllers in a live environment.

I would like to exclude the loading of the controller class from my test integration context. How can this be achieved?

+5
source share
1 answer

You can use spring profiles for this (link How to install spring profile in package? ) Using

  <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <!-- define profile beans at the end of the configuration file --> <beans profile="test"> <context:component-scan base-package="com.main"> <context:exclude-filter expression="com.main.*Controller" type="regex"/> </context:component-scan> </beans> <beans profile="!test"> <context:component-scan base-package="com.main"/> </beans> 

and annotating a test with @ActiveProfile("test")

EDIT:

If your xml does not define the <component:scan> , you can control the scanning of packages from your unit test using the java configuration. Then the controllers can be excluded using @ComponentScan excludeFilter as follows:

 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader = AnnotationConfigContextLoader.class) public class HelperTest { @Configuration @ComponentScan(basePackages = "yourPackage", excludeFilters = @ComponentScan.Filter(value = Controller.class, type = FilterType.ANNOTATION)) @ImportResource(locations = "classpath:context.xml") static class TestConfiguration { } 
+3
source

Source: https://habr.com/ru/post/1261580/


All Articles