简体   繁体   中英

How to use different static content in unit tests?

I' writing tests in java using JUnit. I've tried something like this (simplified):

public class Main() {

    static int a = 0; 

    public static void main(String[] args) {
        a++;
        System.out.println(a); 
    }
}

public class TestA() {
    @Test
    public void test() {
        Main.main(null);
    }
}

public class TestB() {
    @Test
    public void test() {
        Main.main(null);
    }
}

@RunWith(Suite.class)
@Suite.SuiteClasses({
    TestA.class,
    TestB.class
})
public class All { }

I want my test to be run with static content individual for each test. Is it possible to achieve this behaviours?

In your example, the static state is package-private, so your test class can reset it in a @Before method (given it is declared in the same package). This can be tricky for more complex state and does not solve the issue for private static state.

The only way I know of to prevent static state to spread between unit tests is having a new JVM for each test being run. Depending on your JUnit runner, it may provide a way to "fork" the JVM in different ways, achieving your desired result.

For instance, the Apache Ant JUnit runner provides an argument forkMode which can be set to perTest (see documentation https://ant.apache.org/manual/Tasks/junit ). With this setting, Ant will create a JVM for Junit on each single test, effectively having independent "static states" for each test.

The Eclipse JUnit runner unfortunately does not provide such capability (see JUnit Fork-Mode in Java Classes ), you will have to run your tests one by one there.

That being said, if you are unable to test your software units without side effect, it might be a sign of bad design. Refactoring the tested code might be the best solution if available .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM