日期提供者, 使用它而不是直接取得系统时间, 方便测试. 平时使用DEFAULT,测试时替换为DummyClock,可准确控制时间变化而不用Thread.sleep()等待时间流逝.
| 8 | * 平时使用DEFAULT,测试时替换为DummyClock,可准确控制时间变化而不用Thread.sleep()等待时间流逝. |
| 9 | */ |
| 10 | public class ClockUtil { |
| 11 | |
| 12 | private static Clock instance = new DefaultClock(); |
| 13 | |
| 14 | /** |
| 15 | * 计算流逝的时间 |
| 16 | */ |
| 17 | public static long elapsedTime(long beginTime) { |
| 18 | return currentTimeMillis() - beginTime; |
| 19 | } |
| 20 | |
| 21 | /** |
| 22 | * 切换为DummyClock,使用系统时间为初始时间, 单个测试完成后需要调用useDefaultClock()切换回去. |
| 23 | */ |
| 24 | public static synchronized DummyClock useDummyClock() { |
| 25 | instance = new DummyClock(); |
| 26 | return (DummyClock) instance; |
| 27 | } |
| 28 | |
| 29 | /** |
| 30 | * 切换为DummyClock,单个测试完成后需要调用useDefaultClock()切换回去. |
| 31 | */ |
| 32 | public static synchronized DummyClock useDummyClock(long timeStampMills) { |
| 33 | instance = new DummyClock(timeStampMills); |
| 34 | return (DummyClock) instance; |
| 35 | } |
| 36 | |
| 37 | /** |
| 38 | * 切换为DummyClock,单个测试完成后需要调用useDefaultClock()切换回去. |
| 39 | */ |
| 40 | public static synchronized DummyClock useDummyClock(Date date) { |
| 41 | instance = new DummyClock(date); |
| 42 | return (DummyClock) instance; |
| 43 | } |
| 44 | |
| 45 | /** |
| 46 | * 重置为默认Clock |
| 47 | */ |
| 48 | public static synchronized void useDefaultClock() { |
| 49 | instance = new DefaultClock(); |
| 50 | } |
| 51 | |
| 52 | /** |
| 53 | * 系统当前时间 |
| 54 | */ |
| 55 | public static Date currentDate() { |
| 56 | return instance.currentDate(); |
| 57 | } |
| 58 | |
| 59 | /** |
| 60 | * 系统当前时间戳 |
| 61 | */ |
| 62 | public static long currentTimeMillis() { |
| 63 | return instance.currentTimeMillis(); |
| 64 | } |
| 65 | |
| 66 | /** |
| 67 | * 操作系统启动到现在的纳秒数,与系统时间是完全独立的两个时间体系 |
nothing calls this directly
no outgoing calls
no test coverage detected