Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load application context Once for multiple Test classes

I have two test classes

public class Test_1 {

    @Autowired
    private Gson gson;

    @Test 
    public void test_1_1 () {
        assertNotNull(gson);
    }
}

public class Test_2 {

    @Autowired
    private Gson gson;

    @Test 
    public void test_2_1 () {
        assertNotNull(gson);
    }
}

Both require spring application Context. But instead of giving @RnWith(SpringRunner.class) & @ContextConfiguration(classes = {Config.class)}) on both the classes I want to initialise Application Context once. And at the same time I should be able to run single(any test through eclipse) test. Is this possible.

Gone through this : test suite inside spring context. but its loading the application context but not available in Test_1 or Test_2 (gson is null).

like image 522
pvjhs Avatar asked Nov 29 '25 04:11

pvjhs


1 Answers

Yes, this is perfectly possible. All you have to do is to use the same locations attribute in your test classes:

@ContextConfiguration(locations = "classpath:test-context.xml") Spring caches application contexts by locations attribute so if the same locations appears for the second time, Spring uses the same context rather than creating a new one.

I wrote an article about this feature: Speeding up Spring integration tests. Also it is described in details in Spring documentation: 9.3.2.1 Context management and caching.

This has an interesting implication. Because Spring does not know when JUnit is done, it caches all context forever and closes them using JVM shutdown hook. This behavior (especially when you have a lot of test classes with different locations) might lead to excessive memory usage, memory leaks, etc. Another advantage of caching context.

source this answer

like image 57
best wishes Avatar answered Nov 30 '25 20:11

best wishes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!