Junit - run set up method once Ask Question

Junit - run set up method once Ask Question

I set up a class with a couple of tests and rather than using @Before I would like to have a setup method that executes only once before all tests. Is that possible with Junit 4.8?

ベストアンサー1

Although I agree with @assylias that using @BeforeClass is a classic solution it is not always convenient. The method annotated with @BeforeClass must be static. It is very inconvenient for some tests that need instance of test case. For example Spring based tests that use @Autowired to work with services defined in spring context.

In this case I personally use regular setUp() method annotated with @Before annotation and manage my custom static(!) boolean flag:

private static boolean setUpIsDone = false;
.....
@Before
public void setUp() {
    if (setUpIsDone) {
        return;
    }
    // do the setup
    setUpIsDone = true;
}

おすすめ記事