2017-05-25 55 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將始終假定您已正確初始化要測試的類,依賴關係解析不是它的可響應性。

而且,正如你所看到的,春天不會讓事件該測試開始,如果依賴不解決