16
16
17
17
package org .metafacture .flowcontrol ;
18
18
19
- import static org .junit .Assert .assertTrue ;
20
-
21
19
import org .metafacture .framework .ObjectReceiver ;
22
20
21
+ import org .junit .Assert ;
23
22
import org .junit .Before ;
24
23
import org .junit .Test ;
25
24
import org .mockito .Mock ;
26
25
import org .mockito .MockitoAnnotations ;
27
26
28
- import java .time .Duration ;
29
- import java .time .Instant ;
27
+ import java .util .function .Consumer ;
30
28
31
29
/**
32
30
* Tests for class {@link ObjectSleeper}.
33
- *
34
- * @author Tobias Bülte
35
- *
36
- */
31
+ *
32
+ * @author Tobias Bülte
33
+ */
37
34
public final class ObjectSleeperTest {
38
35
36
+ private static final int PROCESS_OVERHEAD_MILLISECONDS = 100 ;
37
+
38
+ private static final int MILLISECONDS_PER_SECOND = 1_000 ;
39
+ private static final int NANOSECONDS_PER_MILLISECOND = 1_000_000 ;
40
+
39
41
@ Mock
40
42
private ObjectReceiver <String > receiver ;
41
43
@@ -46,20 +48,39 @@ public void setup() {
46
48
47
49
@ Test
48
50
public void shouldTestIfClockedTimeExceedsDuration () {
49
- long sleepTime = 100 ;
51
+ final int sleepTime = 1234 ;
52
+ assertSleep (sleepTime , s -> s .setSleepTime (sleepTime ));
53
+ }
50
54
51
- ObjectSleeper <String > objectSleeper = new ObjectSleeper <>();
52
- objectSleeper .setReceiver (receiver );
53
- objectSleeper .setSleepTime (sleepTime );
54
- Instant start = Instant .now ();
55
- objectSleeper .process (null );
56
- Instant end = Instant .now ();
55
+ @ Test
56
+ public void shouldTestIfClockedTimeExceedsDurationInMilliseconds () {
57
+ final int sleepTime = 567 ;
58
+ assertSleep (sleepTime , s -> {
59
+ s .setSleepTime (sleepTime );
60
+ s .setTimeUnit ("MILLISECONDS" );
61
+ });
62
+ }
63
+
64
+ @ Test
65
+ public void shouldTestIfClockedTimeExceedsDurationInSeconds () {
66
+ final int sleepTime = 1 ;
67
+ assertSleep (sleepTime * MILLISECONDS_PER_SECOND , s -> {
68
+ s .setSleepTime (sleepTime );
69
+ s .setTimeUnit ("SECOND" );
70
+ });
71
+ }
57
72
58
- Duration timeElapsed = Duration .between (start , end );
73
+ private void assertSleep (final long expectedMillis , final Consumer <ObjectSleeper > consumer ) {
74
+ final ObjectSleeper <String > objectSleeper = new ObjectSleeper <>();
75
+ objectSleeper .setReceiver (receiver );
76
+ consumer .accept (objectSleeper );
59
77
60
- assertTrue (timeElapsed .toMillis () >= sleepTime );
78
+ final long startTime = System .nanoTime ();
79
+ objectSleeper .process (null );
80
+ final long actualMillis = (System .nanoTime () - startTime ) / NANOSECONDS_PER_MILLISECOND ;
61
81
82
+ Assert .assertTrue ("sleep time too short: " + actualMillis , actualMillis >= expectedMillis );
83
+ Assert .assertTrue ("sleep time too long: " + actualMillis , actualMillis < expectedMillis + PROCESS_OVERHEAD_MILLISECONDS );
62
84
}
63
85
64
-
65
86
}
0 commit comments