【问题标题】:Why does spring try to inject dependencies into mocked object?为什么 spring 尝试将依赖项注入到模拟对象中?
【发布时间】: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


    【解决方案1】:

    您必须像使用testBean 一样将anotherTestbean 声明为spring 托管bean。 当spring尝试将anotherTestBean放入TestBean但spring上下文中没有这样的bean时会发生错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-24
      • 2011-10-14
      • 1970-01-01
      相关资源
      最近更新 更多