Search code examples
javaspringjunitapplicationcontext

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.


Solution

  • It's not direct answer, so I'd would not mark as solution. But hope it's helpful.

    Generally I see three options.

    1. As VinayVeluri answered nicely. Create separate contexts and launch them in every tests separately.

    2. Create context one time per all tests. Just like here: Reuse spring application context across junit test classes It's a big optimization for testing all tests at once.

    3. Mix those two first points. Create one smaller context only for testing purpose. Mock that, what's never is tested but can throw NPE etc. Like here: Injecting Mockito mocks into a Spring bean to boost up context build. And re-use it like in point 2. One time build for all tests. Personally I'd go with that one.

    4. This one waiting for answer about some kind of smart test runner, which creates minimum needed context per test.