package com.grunka.random.fortuna;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

import static org.junit.Assert.assertEquals;

public class PrefetchingSupplierTest {
    private ExecutorService executorService;

    @Before
    public void setUp() {
        executorService = Executors.newFixedThreadPool(2);
    }

    @After
    public void tearDown() {
        executorService.shutdown();
    }

    @Test
    public void shouldGetValues() {
        AtomicInteger number = new AtomicInteger();
        PrefetchingSupplier<String> prefetcher = new PrefetchingSupplier<>(() -> "hello " + number.getAndIncrement(), executorService);
        assertEquals("hello 0", prefetcher.get());
        assertEquals("hello 1", prefetcher.get());
        assertEquals("hello 2", prefetcher.get());
    }
}

@@ -102,16 +102,140 @@
 .Test;%0A%0A
+import java.util.ArrayList;%0Aimport java.util.Arrays;%0Aimport java.util.List;%0Aimport java.util.concurrent.ExecutionException;%0A
 import j
@@ -271,16 +271,16 @@
 ervice;%0A
-
 import j
@@ -310,16 +310,52 @@
 cutors;%0A
+import java.util.concurrent.Future;%0A
 import j
@@ -526,16 +526,50 @@
 Service;
+%0A    private List%3CInteger%3E sleeps;
 %0A%0A    @B
@@ -596,24 +596,95 @@
 d setUp() %7B%0A
+        sleeps = new ArrayList%3C%3E(Arrays.asList(200, 150, 100, 50, 0));%0A
         exec
@@ -726,17 +726,17 @@
 eadPool(
-2
+5
 );%0A    %7D
@@ -1148,32 +1148,32 @@
 fetcher.get());%0A
-
         assertEq
@@ -1212,11 +1212,920 @@
 );%0A    %7D
+%0A%0A    @Test%0A    public void shouldBeOrderedAndCorrectNumberOfOutputs() throws ExecutionException, InterruptedException %7B%0A        AtomicInteger number = new AtomicInteger();%0A        PrefetchingSupplier%3CInteger%3E prefetcher = new PrefetchingSupplier%3C%3E(() -%3E %7B%0A            sleep();%0A            return number.getAndIncrement();%0A        %7D, executorService);%0A        List%3CInteger%3E values = new ArrayList%3C%3E();%0A        List%3CFuture%3C?%3E%3E futures = new ArrayList%3C%3E();%0A        for (int i = 0; i %3C 5; i++) %7B%0A            futures.add(executorService.submit(() -%3E values.add(prefetcher.get())));%0A        %7D%0A        for (Future%3C?%3E future : futures) %7B%0A            future.get();%0A        %7D%0A        assertEquals(Arrays.asList(0, 1, 2, 3, 4), values);%0A    %7D%0A%0A    private void sleep() %7B%0A        try %7B%0A            Thread.sleep(sleeps.remove(0));%0A        %7D catch (InterruptedException e) %7B%0A            throw new Error(e);%0A        %7D%0A    %7D
 %0A%7D%0A

Test verifying that the prefetcher doesn't serve outputs in the wrong order