为了避免模拟代码中的静态变量在测试期间影响其他测试单元,建议采用使用依赖注入或者模拟框架Mockito等方法对静态变量进行模拟。例如:
public class MyService {
    private static int count = 0;
    
    public void doSomething() {
        count++;
        // do something
    }
    
    public int getCount() {
        return count;
    }
}
public class MyServiceTest {
    @Test
    public void testDoSomething() {
        MyService myService = new MyService();
        myService.doSomething();
        myService.doSomething();
        myService.doSomething();
        assertEquals(3, myService.getCount());
    }
}
此时,在测试过程中会将静态变量count模拟为当次测试环境中的局部变量,避免对其他测试单元的影响。