I have a bean whose business logic loads beans of a certain type from the ApplicationContext in order to process them.
For my jUnit tests, I would like to create some dummy beans within my unit test class and see if my bean under test properly processes them. However, I am not sure what the best way to accomplish this is.
If I just declare my inner class within my test class, Spring will not have it as part of its application context. I realize that I could inject my application context within my jUnit class, and then use appContext.registerPrototype() to add it, however, I thought there might be a cleaner way using annotations.
I've tried to annotate the internal class with @Component, but not surprisingly, it did not work.
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");
}
}
Not surprisingly, I get the following error message:
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)}
Is there any way of doing this?
You need to make your inner class static
; Spring can't instantiate a non-static
inner class as a bean. If there really is a valid reason why it needs to be non-static
, you could create it manually in an @Bean
method.