mercredi 30 janvier 2019

spring attempt to inject @Autowired dependencies in a Mocked instance

I have the following classes: com.foo.pkgx:

@Component public class A {}

@Component public class B {
    @Autowired A a;
}

com.foo.pkgy:

@Component public class C {
    @Autowired B b;
}

I.E. dependency-wise: C -> B -> A

When executing the following spock Specification:

@Configuration
@ComponentScan(basePackages = ["com.foo.pkgy"])
class Config {
    def mockFactory = new DetachedMockFactory()

    @Bean
    B b() {mockFactory.Mock(B)};
}

@ContextConfiguration(classes = Config)
class CSpec extends Specification {

    @Autowired
    C c;

    def "sanity"() {
        expect: c
    }
}

The test fails initialization:

Caused by: org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'c': 
Injection of autowired dependencies failed; 
nested exception is org.springframework.beans.factory.BeanCreationException: 
Could not autowire field: com.foo.pkgx.B com.foo.pkgy.C.b; 
nested exception is org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'b': 
Injection of autowired dependencies failed; 
nested exception is org.springframework.beans.factory.BeanCreationException: 
Could not autowire field: com.foo.pkgx.A com.foo.pkgx.B.a; 
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No qualifying bean of type [com.foo.pkgx.A] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

I read this as "tried to wire A into B, but failed". I wasn't expecting B to undergo autowiring, as it is mocked.

Could someone shed some light?

Thanks!

Aucun commentaire:

Enregistrer un commentaire