首页 文章

为什么spring会尝试将依赖项注入mock对象?

提问于
浏览
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"));
}

}

}

ContextClass:

@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;

}

AnotherTestBean.class:

@Component
public class AnotherTestBean {

}

现在,如果我运行此代码,我会收到一个错误:

org.springframework.beans.factory.NoSuchBeanDefinitionException:没有为依赖项找到类型为[info.imapping.application.configuration.context.AnotherTestBean]的限定bean:预期至少有1个bean符合此依赖项的autowire候选者 . 依赖注释:{@ org.springframework.beans.factory.annotation.Autowired(required = true)}

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

如果我在 TestClass 中使用 @ReplaceWithMock ,它就可以了 . 但我更喜欢在上下文文件中设置我的模拟 .

1 回答

  • 0

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

相关问题