Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell spring to only load the needed beans for the JUnit test?

A simple question that might have an advanced answer.

The Question: My question is, is there a way to instantiate only the classes, in your application context, needed for that specific JUnit test ?

The Reason: My application context is getting quite big. I also do a lot of integration tests so you I guess you would understand when I say that every time I run a test all the classes in my application context get instantiated and this takes time.

The Example:

Say class Foo inject only bar

public class Foo {  @Inject Bar bar;  @Test public void testrunSomeMethod() throws RegisterFault {     bar.runSomeMethod(); } 

but the application context has beans foobar and bar. I know this is not a vaild application context but rest assure all my code works.

<beans>      <bean id="foobar" class="some.package.FooBar"/>      <bean id="bar" class="some.package.Bar"/> <beans> 

So how do I tell spring to only instantiate Bar and ignore FooBar for the test class foo.

Thank you.

like image 693
SandMan Avatar asked Aug 18 '16 09:08

SandMan


People also ask

How does Spring know which bean to use?

The identifier of the parameter matches the name of one of the beans from the context (which is the same as the name of the method annotated with @Bean that returns its value). In this case, Spring chooses that bean for which the name is the same as the parameter.

How do you load all beans in Spring?

In Spring Boot, you can use appContext. getBeanDefinitionNames() to get all the beans loaded by the Spring container.


1 Answers

Consider adding default-lazy-init="true" to your spring context xml beans tag (or add lazy-init="true" to those specific beans that take a long time starting up). This will ensure that only those beans are created that called with applicationContext.getBean(class-or-bean-name) or injected via @Autowired / @Inject into your tests. (Some other types of beans like @Scheduled beans will be created nevertheless but you need to check if that's a problem or not)

(if you use spring Java configuration, add @Lazy to the config files)

Caveat - If there is a bean that is not initialized explicitly with applicationContext.getBean() or injected as a dependency used by the bean obtained by using applicationContext.getBean(), then that bean will NO LONGER be constructed or initialized. Depending upon your application, that can cause things to fail OR not. Maybe you can selectively mark those beans as lazy-init="false"

like image 96
Deepak Avatar answered Sep 16 '22 16:09

Deepak