2

私はMockitoを初めて使用し、質問があります。

アプリに Spring の依存性注入を使用していて、コンポーネントをテストしようとしています。次のようなテストがあります。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(// @formatter:off
    loader = SpringockitoAnnotatedContextLoader.class,
    classes = { TestContext.class }) // @formatter:on
public class TestClass {

@Autowired
private TestBean testBean;

@Test
public void testSomething() {

// do anything
assertTrue(testBean.getClass().getName().equals("TestBean"));
}

}

}

コンテキストクラス:

@Configuration
public class TestContext {

@Bean(name = "testBean")
public TestBean getTestBean() {
    return Mockito.mock(TestBean.class);
}

} 

TestBean.class:

@Component
public class TestBean {

@Autowired
private AnotherTestBean anotherTestBean;

}

別のTestBean.class:

@Component
public class AnotherTestBean {

}

このコードを実行すると、次の原因によるエラーが発生します。

org.springframework.beans.factory.NoSuchBeanDefinitionException: 依存関係のタイプ [info.imapping.application.configuration.context.AnotherTestBean] の適格な Bean が見つかりません: この依存関係の自動配線候補として適格な Bean が少なくとも 1 つ必要です。依存関係アノテーション: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

これは、Spring がモック Bean に依存関係を注入しようとしたことを意味します。誰かがこの動作を防ぐ方法を教えてもらえますか?

で使用する@ReplaceWithMockTestClass動作します。しかし、コンテキスト ファイルにモックアップを設定することをお勧めします。

4

1 に答える 1

0

anotherTestbeanで行ったように、Spring Managed Bean として宣言する必要がありますtestBean。スプリングが入れようとするとエラーが発生しますがanotherTestBeanTestBeanスプリングコンテキストにはそのような Bean がありません。

于 2014-10-24T14:23:04.963 に答える