junit 方法间变量共享问题

junit 变量共享问题

猜猜以下代码的执行结果:

// 该注解指定junit按方法名的顺序执行方法
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class JunitVariableTest {
    private static int index = 0;
    private static String sContent;
    private String content;

    @Test
    public void first() {
        System.out.println("exe first method ...");
        System.out.println("before init sContent: [" + sContent + "], content: [" + content + "], index: [" + index + "]");
        content = "hello world";
        index++;
        sContent = "static hello world";
        System.out.println("after init sContent: [" + sContent + "], content: [" + content + "], index: [" + index + "]");
    }

    @Test
    public void second() {
        System.out.println();
        System.out.println("exe second method ...");
        System.out.println("whether sContent had initialized ? sContent: [" + sContent + "]");
        System.out.println("whether content had initialized ? content: [" + content + "]");
        System.out.println("whether index had growth ? index: [" + index + "]");
    }
}

答案揭晓:

exe first method ... before init sContent: [null], content: [null], index: [0]
after init sContent: [static hello world], content: [hello world], index: [1]

exe second method ... whether sContent had initialized ? sContent: [static hello world]
whether content had initialized ? content: [null]
whether index had growth ? index: [1]

结论:
- 虽然在first()方法中对非静态成员变量进行了赋值,但在执行另一个Test方法时,并未共享前面方法的执行结果
- 先执行方法对静态成员变量的改变会影响到后续的方法

你可能感兴趣的:(java,junit)