我的课程看起来大致如下:
@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寻找我的组件,以便它知道如何自动装配它?
感谢。
答案 0 :(得分:1)
您应该启用组件扫描
@Configuration
@ComponentScan(basePackages = { MyServicePackage })
static class ContextConfiguration {
...