junit 方法间变量共享问题

本文通过一个实例演示了在JUnit测试框架中,静态变量如何在不同测试方法间共享状态,而非静态变量则不会共享。揭示了静态变量在测试方法间的可见性及影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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方法时,并未共享前面方法的执行结果
- 先执行方法对静态成员变量的改变会影响到后续的方法

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值