2017-05-25 59 views
1

我有这个类弹簧试验如果类解决它的自动装配依赖

@Component("A") 
public class A { 
    private B b; 

    @Autowired 
    public A(B b) { 
     this.b = b; 
    } 
} 

和其他类

@Component("B") 
public class B { 

    public B() { 

    } 
} 

现在我已经写了这个测试

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(loader=AnnotationConfigContextLoader.class) 
public class ConstructorAutowiredTest { 

    @Configuration 
    static class ContextConfiguration { 
     @Bean 
     public B getBBean() { 
      B b = new B(); 
      return b; 
     } 
    } 

    @Autowired 
    private B b; 


    @Test 
    public void isDependencyResolved() { 
     assertNotNull(b); 
    } 
} 

它的工作原理好。但有什么方法可以测试这个B bean是否自动注入到A中。我想这样的东西,但显然它不工作。

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(loader=AnnotationConfigContextLoader.class) 
public class ConstructorAutowiredTest { 

    @Configuration 
    static class ContextConfiguration { 
     @Bean 
     public B getBBean() { 
      B b = new B(); 
      return b; 
     } 
    } 

    @Autowired 
    private A a; 

    @Autowired 
    private B b; 


    @Test 
    public void isDependencyResolved() { 
     assertNotNull(b); 
     assertNotNull(a); 
    } 
} 

例外:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.abc.ConstructorAutowiredTest': 
Unsatisfied dependency expressed through field 'a'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No qualifying bean of type 'com.abc.A' available: expected at least 1 bean which qualifies as autowire candidate. 
Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 
+0

好。很明显,测试失败了,因为依赖性没有被解决,至少你现在知道了。你的问题到底是什么? –

+0

我没有看到你想在这里测试的东西。您只是测试您的测试部署配置。重点是什么? –

+0

@Pablo我知道。但是我无法弄清楚如何在这里指定'@ComponentScan(“com.abc”)'这样的东西。 – sof

回答

0

也可以添加到您的配置的组件扫描其上传你的@Component( “A”)

这样的:

@Configuration 
@ComponentScan("some.package") 
static class ContextConfiguration { 
    @Bean 
    public B getBBean() { 
     B b = new B(); 
     return b; 
    } 
} 

这将解决你的异常,然后你可以断言你的Bean A,如果它插入了B.

-1

据我了解你的问题,我认为你正在使用JUnit来测试不是单元测试的东西,而是更接近集成测试的东西,它不在JUnit的范围之内。

JUnit将始终假定您已正确初始化要测试的类,依赖关系解析不是它的可响应性。

而且,正如你所看到的,春天不会让事件该测试开始,如果依赖不解决