I've a situation in which I'd like to unit test a couple of classes which are wired together with spring autowiring. In my unit test I'd like to specify which classes need to be wired together, rather then specifying an entire package which is scanned for autowiring. I'd like to use annotations only for this configuration.
The solution I've found so far makes use of the @ComponentScan annotation with some includeFilters. Is there no better way to do the same?
Class A
package example.a;
import org.springframework.stereotype.Component;
@Component
public class A {
}
Class B
package example.b;
import org.springframework.*;
import example.a.A;
@Component
public class B {
@Autowired
private A a;
public A getA() {
return a;
}
}
Unit test
package example.b;
import org.*;
import org.springframework.*;
import example.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)
public class BTest {
@Configuration
@ComponentScan(basePackages={"example"}, useDefaultFilters=false,
includeFilters = {
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = A.class),
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = B.class),
})
static class ContextConfiguration{
}
@Autowired
private B b;
@Test
public void testAIsAutowiredInB(){
Assert.assertNotNull( b.getA() );
}
}
Aucun commentaire:
Enregistrer un commentaire