3

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).

pvjhs
  • 357
  • 1
  • 4
  • 16
  • Possible duplicate of [Reuse spring application context across junit test classes](https://stackoverflow.com/questions/8501975/reuse-spring-application-context-across-junit-test-classes) – best wishes Apr 15 '18 at 13:42

1 Answers1

1

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

best wishes
  • 3,090
  • 1
  • 19
  • 42