我有一个 bean,其业务逻辑从 ApplicationContext 加载特定类型的 bean 以处理它们。
对于我的 jUnit 测试,我想在我的单元测试类中创建一些虚拟 bean 并查看我的被测 bean 是否正确处理它们。但是,我不确定实现此目标的最佳方法是什么。
如果我只是在我的测试类中声明我的内部类,Spring 不会将它作为其应用程序上下文的一部分。我意识到我可以在我的 jUnit 类中注入(inject)我的应用程序上下文,然后使用 appContext.registerPrototype() 添加它,但是,我认为使用注释可能有更简洁的方法。
我试过用@Component注解内部类,但毫不奇怪,它没有用。
public class PatchEngineTest extends TestBase {
@Component
protected class Patch1 extends PatchBaseImpl implements Patch{
public void applyPatch() throws Exception {
// does nothing
}
}
@Autowired PatchRepository patchRepository;
@Autowired Patch1 patch1;
@Test
public void test() {
fail("Not yet implemented");
}
}
毫不奇怪,我收到以下错误消息:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ia.patch.PatchEngineTest$Patch1] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
有什么办法吗?
最佳答案
你需要让你的内部类static
; Spring 不能将非 static
内部类实例化为 bean。如果确实有正当理由需要它是非静态
,您可以在@Bean
方法中手动创建它。
关于java - 如何将内部类添加到 Spring 应用程序上下文以进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19440525/