5

I have a couple of JUnit tests which need a reference for a expensive resource (a WALA class hierachie), which needs about 30s to be created. I would like to share this reference in my whole test suite.

I thought about a static member in a base class which is laziely initiated with a @BeforeClass method. After test is run the JVM should be determined anyway.

Is there any other way to accomplish this? Or any other best practice?

Braiam
  • 1
  • 11
  • 47
  • 78
markusw
  • 1,975
  • 16
  • 28
  • 1
    `@BeforeClass` is the way I'd go – Mureinik May 05 '14 at 14:27
  • Yeah but what about clearing the reference? I cannot determine when the last test was run... – markusw May 05 '14 at 14:28
  • @markusw Then use the corresponding [`AfterClass`](http://junit.sourceforge.net/javadoc/org/junit/AfterClass.html). – Giovanni Botta May 05 '14 at 14:30
  • 1
    Why is it important to clear it? How big is it that you can't stand holding on to it until the entire test suite finishes executing? – Mureinik May 05 '14 at 14:30
  • I know `@AfterClass`. But I want the reference to stay alive until the WHOLE suite has been runned. – markusw May 05 '14 at 14:31
  • I want to hold it. But is it sure that the JVM is terminating, when the test run ends? Is there any situation in that this reference is kept alive and stays on the heap until the apocalypse? – markusw May 05 '14 at 14:32
  • The Suite is run by JUnit itself, so put the `@BeforeClass` and `@AfterClass` into that. – blalasaadri May 05 '14 at 14:40

1 Answers1

3

Create an explicit test suite (cf. this answer) to run these tests, and use @BeforeClass and @AfterClass on the suite itself (cf. this answer):

@RunWith(Suite.class)
@Suite.SuiteClasses({Test1.class, Test2.class})
public class MySuite {
    @BeforeClass
    public static void initResource() {
        MyExpensiveResource.init();
    }

    @AfterClass
    public static void disposeResource() {
        MyExpensiveResource.dispose();
    }
}
Community
  • 1
  • 1
David Moles
  • 48,006
  • 27
  • 136
  • 235
  • If for some reason test suites won't work for you, [this answer](http://stackoverflow.com/a/153538/27358) suggests looking into something called [SpringJUnit4ClassRunner](http://docs.spring.io/spring/docs/2.5.x/api/org/springframework/test/context/junit4/SpringJUnit4ClassRunner.html). I've never used it so I can't speak for it myself. – David Moles May 08 '14 at 17:24
  • I thought about it, but what if I want to run a single test from the suite. I now came up with a lazy initialization in an abstract base class.. – markusw May 09 '14 at 07:44
  • I do'nt use Spring for now. Maybe in a later iteration it will be added, so I will reevaluate the usage of the spring junit runner. – markusw May 09 '14 at 07:44