【发布时间】:2014-10-24 14:16:37
【问题描述】:
我对 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:预计至少有1个bean有资格作为此依赖的自动装配候选者。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}
这意味着 Spring 试图将依赖项注入到我的模拟 bean 中。有人可以告诉我如何防止这种行为吗?
如果我在TestClass 中使用@ReplaceWithMock,它可以工作。但我更喜欢在上下文文件中设置我的模型。
【问题讨论】:
标签: java spring dependency-injection mockito springockito