如何将内部类添加到Spring应用程序上下文中进行单元测试?

时间:2013-10-18 02:18:13

标签: java spring cdi autowired

我有一个bean,其业务逻辑从ApplicationContext加载某种类型的bean,以便处理它们。

对于我的jUnit测试,我想在我的单元测试类中创建一些虚拟bean,看看我测试的bean是否正确处理它们。但是,我不确定实现这一目标的最佳方法是什么。

如果我只在我的测试类中声明我的内部类,Spring将不会将它作为其应用程序上下文的一部分。我意识到我可以在我的jUnit类中注入我的应用程序上下文,然后使用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)}

有没有办法做到这一点?

2 个答案:

答案 0 :(得分:10)

你需要建立你的内心课static; Spring不能将非static内部类实例化为bean。如果确实有一个合理的原因,为什么它必须是非static,您可以使用@Bean方法手动创建它。

答案 1 :(得分:0)

我也遇到了这个问题,下面是我的解决方法:

@RunWith(SpringRunner.class)
@SpringBootTest
@ComponentScan
@ImportAutoConfiguration
public class FooTest {

    @Component
    public static class Bar {

    }
}

我使用了弹簧靴2.1.4.RELEASE