• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 package org.mockitoutil;
2 
3 import static java.lang.String.format;
4 import static java.lang.System.nanoTime;
5 import static java.util.concurrent.TimeUnit.NANOSECONDS;
6 
7 import java.util.concurrent.TimeUnit;
8 import org.mockito.exceptions.base.MockitoAssertionError;
9 
10 /**
11  * This class can be uses as stopwatch to assert that a given time is elapsed or not.
12  */
13 public class Stopwatch {
14 
15     /**
16      * The start time in nano seconds or <code>null</code> if this stop watch was not started yet
17      */
18     private Long startNanos = null;
19 
20     /**
21      * To create an instance use {@link #createNotStarted()}
22      */
Stopwatch()23     private Stopwatch() {
24     }
25 
26     /**
27      * Return a new and not started {@link Stopwatch}.
28      */
createNotStarted()29     public static Stopwatch createNotStarted() {
30         return new Stopwatch();
31     }
32 
start()33     public void start() {
34         if (startNanos != null)
35             throw new IllegalStateException("This stop watch is already started!");
36 
37         startNanos = nanoTime();
38     }
39 
assertElapsedTimeIsMoreThan(long expected, TimeUnit unit)40     public void assertElapsedTimeIsMoreThan(long expected, TimeUnit unit) {
41         long elapsedNanos = elapsedNanos();
42         long expectedNanos = unit.toNanos(expected);
43 
44         if (elapsedNanos <= expectedNanos)
45             fail("Expected that more than %dms elapsed! But was: %dms", expectedNanos, elapsedNanos);
46     }
47 
assertElapsedTimeIsLessThan(long expected, TimeUnit unit)48     public void assertElapsedTimeIsLessThan(long expected, TimeUnit unit) {
49         long elapsedNanos = elapsedNanos();
50         long expectedNanos = unit.toNanos(expected);
51 
52         if (elapsedNanos >= expectedNanos)
53             fail("Expected that less than %dms elapsed! But was: %dms", expectedNanos, elapsedNanos);
54     }
55 
elapsedNanos()56     private long elapsedNanos() {
57         if (startNanos == null)
58             throw new IllegalStateException("This stop watch is not started!");
59         return nanoTime() - startNanos;
60     }
61 
fail(String message, long expectedNanos, long elapsedNanos)62     private static void fail(String message, long expectedNanos, long elapsedNanos) {
63         throw new MockitoAssertionError(format(message, NANOSECONDS.toMillis(expectedNanos), NANOSECONDS.toMillis(elapsedNanos)));
64     }
65 }
66