|
| 1 | +package com.baeldung.time; |
| 2 | + |
| 3 | +import static org.junit.Assert.assertEquals; |
| 4 | + |
| 5 | +import java.time.Duration; |
| 6 | +import java.time.Instant; |
| 7 | +import java.util.concurrent.TimeUnit; |
| 8 | + |
| 9 | +import org.apache.commons.lang3.time.StopWatch; |
| 10 | +import org.junit.Test; |
| 11 | + |
| 12 | +public class ElapsedTimeUnitTest { |
| 13 | + |
| 14 | + @Test |
| 15 | + public void givenRunningTask_whenMeasuringTimeWithCurrentTimeMillis_thenGetElapsedTime() throws InterruptedException { |
| 16 | + long start = System.currentTimeMillis(); |
| 17 | + |
| 18 | + simulateRunningTask(); |
| 19 | + |
| 20 | + long finish = System.currentTimeMillis(); |
| 21 | + |
| 22 | + long timeElapsed = finish - start; |
| 23 | + |
| 24 | + assertEquals(true, (2000L <= timeElapsed) && (timeElapsed <= 3000L)); |
| 25 | + } |
| 26 | + |
| 27 | + @Test |
| 28 | + public void giveRunningTask_whenMeasuringTimeWithNanoTime_thenGetElapsedTime() throws InterruptedException { |
| 29 | + long start = System.nanoTime(); |
| 30 | + |
| 31 | + simulateRunningTask(); |
| 32 | + |
| 33 | + long finish = System.nanoTime(); |
| 34 | + |
| 35 | + long timeElapsed = finish - start; |
| 36 | + |
| 37 | + assertEquals(true, (2000000000L <= timeElapsed) && (timeElapsed <= 3000000000L)); |
| 38 | + } |
| 39 | + |
| 40 | + @Test |
| 41 | + public void givenRunningTask_whenMeasuringTimeWithStopWatch_thenGetElapsedTime() throws InterruptedException { |
| 42 | + StopWatch watch = new StopWatch(); |
| 43 | + watch.start(); |
| 44 | + |
| 45 | + simulateRunningTask(); |
| 46 | + |
| 47 | + watch.stop(); |
| 48 | + |
| 49 | + long timeElapsed = watch.getTime(); |
| 50 | + |
| 51 | + assertEquals(true, (2000L <= timeElapsed) && (timeElapsed <= 3000L)); |
| 52 | + } |
| 53 | + |
| 54 | + @Test |
| 55 | + public void givenRunningTask_whenMeasuringTimeWithInstantClass_thenGetElapsedTime() throws InterruptedException { |
| 56 | + Instant start = Instant.now(); |
| 57 | + |
| 58 | + simulateRunningTask(); |
| 59 | + |
| 60 | + Instant finish = Instant.now(); |
| 61 | + |
| 62 | + long timeElapsed = Duration.between(start, finish).toMillis(); |
| 63 | + |
| 64 | + assertEquals(true, (2000L <= timeElapsed) && (timeElapsed <= 3000L)); |
| 65 | + } |
| 66 | + |
| 67 | + /** |
| 68 | + * Simulate task running for 2.5 seconds. |
| 69 | + * |
| 70 | + * @throws InterruptedException |
| 71 | + */ |
| 72 | + private static void simulateRunningTask() throws InterruptedException { |
| 73 | + TimeUnit.MILLISECONDS.sleep(2500); // 2.5 seconds |
| 74 | + |
| 75 | + } |
| 76 | +} |
0 commit comments