Java 为什么spring尝试将依赖项注入模拟对象?

Java 为什么spring尝试将依赖项注入模拟对象?,java,spring,dependency-injection,mockito,springockito,Java,Spring,Dependency Injection,Mockito,Springockito,我对莫基托很陌生,有一个问题 我正在为我的应用程序使用Spring的依赖注入,并尝试测试组件。我有一个这样的测试: @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(// @formatter:off loader = SpringockitoAnnotatedContextLoader.class, classes = { TestContext.class }) // @formatter:on pub

我对莫基托很陌生,有一个问题

我正在为我的应用程序使用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;

}
@Component
public class AnotherTestBean {

}
另一个TestBean.class:

@Component
public class TestBean {

@Autowired
private AnotherTestBean anotherTestBean;

}
@Component
public class AnotherTestBean {

}
现在,如果我运行此代码,我会得到一个由以下原因引起的错误:

org.springframework.beans.factory.NoSuchBeanDefinitionException:未找到依赖项类型为[info.imapping.application.configuration.context.AnotherTestBean]的符合条件的bean:至少需要1个符合此依赖项autowire候选项条件的bean。依赖项注释:{@org.springframework.beans.factory.annotation.Autowired(required=true)}

这意味着Spring试图将依赖项注入到我的模拟bean中。有人能告诉我如何防止这种行为吗


如果在我的
TestClass
中使用
@ReplaceWithMock
,它会工作。但是我更喜欢在上下文文件中设置我的模型。

您必须声明另一个testBean作为spring管理的bean,就像您使用
testBean
一样。 当spring尝试在
TestBean
中放置另一个
TestBean
时会发生错误,但是spring上下文中没有这样的bean