Skip to content

Instantly share code, notes, and snippets.

@takawitter
Created December 2, 2016 12:13

Revisions

  1. takawitter created this gist Dec 2, 2016.
    38 changes: 38 additions & 0 deletions CollectionFixture.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    import static org.junit.Assert.assertEquals;
    import static org.junit.Assert.assertFalse;
    import static org.junit.Assert.assertTrue;

    import java.util.Collection;
    import java.util.Iterator;
    import java.util.function.Consumer;

    public class CollectionFixture<T> {
    public CollectionFixture(Collection<T> collection){
    this.collection = collection;
    this.it = collection.iterator();
    }

    public CollectionFixture<T> assertHasNext(){
    assertTrue(it.hasNext());
    return this;
    }

    public CollectionFixture<T> assertNotHasNext(){
    assertFalse(it.hasNext());
    return this;
    }

    public CollectionFixture<T> assertSize(int expected){
    assertEquals(expected, collection.size());
    return this;
    }

    @SuppressWarnings("unchecked")
    public <U extends T> CollectionFixture<T> next(Consumer<U> c){
    c.accept((U)it.next());
    return this;
    }

    private Collection<T> collection;
    private Iterator<T> it;
    }
    20 changes: 20 additions & 0 deletions SampleTest.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    import static org.junit.Assert.assertEquals;
    import static org.junit.Assert.assertFalse;

    public class SampleTest{
    static class Fruit{}
    static class Apple extends Fruit{boolean bitten;}
    static class Orange extends Fruit{enum Type{Tangerine, Mandarin} Type type = Type.Tangerine;}
    @Test
    public void t() throws Throwable{
    new CollectionFixture<Fruit>(Arrays.asList(new Apple(), new Orange()))
    .next((Apple f) -> {
    assertFalse(f.bitten);
    })
    .next((Orange f) -> {
    assertEquals(f.type, Orange.Type.Tangerine);
    })
    .assertNotHasNext();
    }

    }