Skip to content

Commit

Permalink
Extend and clean up ObjectSleeper test. (#559)
Browse files Browse the repository at this point in the history
  • Loading branch information
blackwinter committed Nov 28, 2024
1 parent 8081fb5 commit 74bc15d
Showing 1 changed file with 39 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,26 +16,28 @@

package org.metafacture.flowcontrol;

import static org.junit.Assert.assertTrue;

import org.metafacture.framework.ObjectReceiver;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.time.Duration;
import java.time.Instant;
import java.util.function.Consumer;

/**
* Tests for class {@link ObjectSleeper}.
*
* @author Tobias Bülte
*
*/
*
* @author Tobias Bülte
*/
public final class ObjectSleeperTest {

private static final int PROCESS_OVERHEAD_MILLISECONDS = 100;

private static final int MILLISECONDS_PER_SECOND = 1_000;
private static final int NANOSECONDS_PER_MILLISECOND = 1_000_000;

@Mock
private ObjectReceiver<String> receiver;

Expand All @@ -46,20 +48,39 @@ public void setup() {

@Test
public void shouldTestIfClockedTimeExceedsDuration() {
long sleepTime = 100;
final int sleepTime = 1234;
assertSleep(sleepTime, s -> s.setSleepTime(sleepTime));
}

ObjectSleeper<String> objectSleeper = new ObjectSleeper<>();
objectSleeper.setReceiver(receiver);
objectSleeper.setSleepTime(sleepTime);
Instant start = Instant.now();
objectSleeper.process(null);
Instant end = Instant.now();
@Test
public void shouldTestIfClockedTimeExceedsDurationInMilliseconds() {
final int sleepTime = 567;
assertSleep(sleepTime, s -> {
s.setSleepTime(sleepTime);
s.setTimeUnit("MILLISECONDS");
});
}

@Test
public void shouldTestIfClockedTimeExceedsDurationInSeconds() {
final int sleepTime = 1;
assertSleep(sleepTime * MILLISECONDS_PER_SECOND, s -> {
s.setSleepTime(sleepTime);
s.setTimeUnit("SECOND");
});
}

Duration timeElapsed = Duration.between(start, end);
private void assertSleep(final long expectedMillis, final Consumer<ObjectSleeper> consumer) {
final ObjectSleeper<String> objectSleeper = new ObjectSleeper<>();
objectSleeper.setReceiver(receiver);
consumer.accept(objectSleeper);

assertTrue(timeElapsed.toMillis() >= sleepTime);
final long startTime = System.nanoTime();
objectSleeper.process(null);
final long actualMillis = (System.nanoTime() - startTime) / NANOSECONDS_PER_MILLISECOND;

Assert.assertTrue("sleep time too short: " + actualMillis, actualMillis >= expectedMillis);
Assert.assertTrue("sleep time too long: " + actualMillis, actualMillis < expectedMillis + PROCESS_OVERHEAD_MILLISECONDS);
}


}

0 comments on commit 74bc15d

Please sign in to comment.