2014-01-21 83 views
1

我有一個類,看起來大致是這樣的:使用Spring組件

@Component 
public class MyService { 
    private MyBean myBean; 

    @Autowired 
    public MyService(MyBean myBean) { 
     this.myBean = myBean; 
    } 
} 

我想測試這個類。如果我可以使用測試MyBean對象在我的測試中自動裝入,那將會很好。我試着這樣做:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(loader = AnnotationConfigContextLoader.class) 
public class MyServiceTest { 
    @Autowired 
    MyService myService; 

    @Configuration 
    static class ContextConfiguration { 
     @Bean 
     public MyBean myBean() { 
      return createMock(myBean); 
     } 
    } 
} 

當我嘗試運行我的測試中,我得到一個錯誤,如:

Injection of autowired dependencies failed No matching bean of type MyService found for dependency: expected at least one bean that is a candidate for this dependency

如何告訴spring查找我的組件,以便它知道如何自動裝配它?

謝謝。

回答

1

您應該啓用組件掃描

@Configuration 
@ComponentScan(basePackages = { MyServicePackage }) 
static class ContextConfiguration { 
...