1 /* 2 * Copyright (c) 2017 Mockito contributors 3 * This program is made available under the terms of the MIT License. 4 */ 5 package org.mockitoutil; 6 7 import static java.lang.String.format; 8 import static java.lang.System.nanoTime; 9 import static java.util.concurrent.TimeUnit.NANOSECONDS; 10 11 import java.util.concurrent.TimeUnit; 12 13 import org.mockito.exceptions.base.MockitoAssertionError; 14 15 /** 16 * This class can be uses as stopwatch to assert that a given time is elapsed or not. 17 */ 18 public class Stopwatch { 19 20 /** 21 * The start time in nano seconds or <code>null</code> if this stop watch was not started yet 22 */ 23 private Long startNanos = null; 24 25 /** 26 * To create an instance use {@link #createNotStarted()} 27 */ Stopwatch()28 private Stopwatch() {} 29 30 /** 31 * Return a new and not started {@link Stopwatch}. 32 */ createNotStarted()33 public static Stopwatch createNotStarted() { 34 return new Stopwatch(); 35 } 36 start()37 public void start() { 38 if (startNanos != null) 39 throw new IllegalStateException("This stop watch is already started!"); 40 41 startNanos = nanoTime(); 42 } 43 assertElapsedTimeIsMoreThan(long expected, TimeUnit unit)44 public void assertElapsedTimeIsMoreThan(long expected, TimeUnit unit) { 45 long elapsedNanos = elapsedNanos(); 46 long expectedNanos = unit.toNanos(expected); 47 48 if (elapsedNanos <= expectedNanos) 49 fail( 50 "Expected that more than %dms elapsed! But was: %dms", 51 expectedNanos, elapsedNanos); 52 } 53 assertElapsedTimeIsLessThan(long expected, TimeUnit unit)54 public void assertElapsedTimeIsLessThan(long expected, TimeUnit unit) { 55 long elapsedNanos = elapsedNanos(); 56 long expectedNanos = unit.toNanos(expected); 57 58 if (elapsedNanos >= expectedNanos) 59 fail( 60 "Expected that less than %dms elapsed! But was: %dms", 61 expectedNanos, elapsedNanos); 62 } 63 elapsedNanos()64 private long elapsedNanos() { 65 if (startNanos == null) throw new IllegalStateException("This stop watch is not started!"); 66 return nanoTime() - startNanos; 67 } 68 fail(String message, long expectedNanos, long elapsedNanos)69 private static void fail(String message, long expectedNanos, long elapsedNanos) { 70 throw new MockitoAssertionError( 71 format( 72 message, 73 NANOSECONDS.toMillis(expectedNanos), 74 NANOSECONDS.toMillis(elapsedNanos))); 75 } 76 77 /** 78 * Waits for specific amount of millis using 'Thread.sleep()'. 79 * Rethrows InterruptedException. 80 */ waitFor(int millis)81 public void waitFor(int millis) { 82 try { 83 Thread.sleep(millis); 84 } catch (InterruptedException e) { 85 throw new RuntimeException(e); 86 } 87 } 88 } 89