如何模拟CurrentTimeMillis返回固定值

   2024-10-08 3470
核心提示:要模拟System.currentTimeMillis()返回固定值,可以通过在代码中使用Mockito或PowerMock等库来模拟System类的行为。下面是一个例

要模拟System.currentTimeMillis()返回固定值,可以通过在代码中使用Mockito或PowerMock等库来模拟System类的行为。下面是一个例子使用Mockito来模拟System.currentTimeMillis()方法返回固定值的示例代码:

import static org.mockito.Mockito.*;public class MockSystem {        public static void main(String[] args) {        // 创建一个mock对象来模拟System类        System system = mock(System.class);                // 设置System.currentTimeMillis()方法返回固定值        when(system.currentTimeMillis()).thenReturn(123456789L);                // 使用mock对象来调用System.currentTimeMillis()方法        long currentTime = system.currentTimeMillis();                // 输出结果        System.out.println("Current time: " + currentTime);    }}

在这个例子中,我们使用Mockito创建了一个System类的mock对象,并通过when(system.currentTimeMillis()).thenReturn(123456789L)方法设置了System.currentTimeMillis()方法返回固定值。当调用system.currentTimeMillis()方法时,它将返回我们指定的固定值。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号