/ /テストでSpringコンポーネントを使用する - java、spring

テストでSpringコンポーネントを使用する - java、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.

私はどのようにautowireを知っているので、私のコンポーネントを探すために春に言うことができますか?

ありがとう。

回答:

回答№1は1

コンポーネントスキャンを有効にする必要があります

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