Sampler { public static <T> T waitForValue(Supplier<T> samplesSupplier, int samplingPeriod, int sampleQueueSize, int maxSamplesThreshold) { CircularFifoBuffer samplesQueue = new CircularFifoBuffer(sampleQueueSize); int samplesTaken = 0; while (!isThresholdReached(samplesTaken, maxSamplesThreshold) && !areAllSamplesEqual(samplesQueue)) { CurrentThread.sleep(samplingPeriod); T nextSample = samplesSupplier.get(); samplesQueue.add(nextSample); ++samplesTaken; } return (T) samplesQueue.get(); }  static T waitForValue(Supplier<T> samplesSupplier, int samplingPeriod,
      int sampleQueueSize, int maxSamplesThreshold);  }
@Test public void sampleChangingValueTest_AllSamplesMatch() { when(supplier.get()).thenReturn(0); Integer finalSample = Sampler .waitForValue(supplier, SAMPLING_PERIOD, SAMPLE_QUEUE_SIZE, MAX_SAMPLES_THRESHOLD); assertEquals((int) finalSample, 0); }
@Test public void sampleChangingValueTest_AllSamplesDiffer_ThresholdReached() { Random random = new Random(); when(supplier.get()) .thenReturn(random.nextInt()) .thenReturn(random.nextInt()) .thenReturn(random.nextInt()) .thenReturn(random.nextInt()) .thenReturn(random.nextInt()); Sampler.waitForValue(supplier, 1, 3, 5); verify(supplier, times(5)).get(); }