Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions src/main/java/net/andreinc/mockneat/abstraction/MockUnit.java
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,46 @@ default <R> MockUnit<R> map(Function<T, R> function) {
return () -> supp;
}

/**
* <p>Returns a generator consisting of the elements of this generator that match the given predicate.</p>
*
* @param predicate The {@code Predicate<T>} applied to the generated value in the intermediary step to determine if it should be returned.
* @return A new MockUnit
*/
default MockUnit<T> filter(Predicate<? super T> predicate) {
notNull(predicate, "predicate");
Supplier<T> supp = () -> {
T val = val();
while (!predicate.test(val)) {
val = val();
}
return val;
};
return () -> supp;
}

/**
* <p>Returns a generator consisting of the distinct elements (according to {@link Object#equals(Object)}) of this generator.</p>
*
* @param function The {@code Function<T,R>} applied to the generated value for check for unique.
* @param <K> The type of the values for check for unique.
* @return A new MockUnit
*/
default <K> MockUnit<T> distinctBy(Function<? super T, ? extends K> function) {
notNull(function, "function");
Set<K> seen = new HashSet<>();
return filter(it -> seen.add(function.apply(it)));
}

/**
* <p>Returns a generator consisting of the distinct elements (according to {@link Object#equals(Object)}) of this generator.</p>
*
* @return A new MockUnit
*/
default MockUnit<T> distinct() {
return distinctBy(Function.identity());
}

/**
* <p>This method is used to transform a {@code MockUnit} into a {@code MockUnitInt}.</p>
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package net.andreinc.mockneat.abstraction;

import org.junit.Test;

import static net.andreinc.mockneat.Constants.*;
import static net.andreinc.mockneat.utils.LoopsUtils.loop;
import static org.junit.Assert.assertEquals;

public class MockUnitFilterMethodTest {

@Test(expected = NullPointerException.class)
public void testFilterNullFunc() {
M.ints().filter(null);
}

@Test(expected = NullPointerException.class)
public void testDistinctByNullFunc() {
M.ints().distinctBy(null);
}

@Test
public void testFilterEven() {
loop(MOCK_CYCLES,
MOCKS,
m -> m.ints().filter(it -> it % 2 == 0).val(),
v -> assertEquals(0, v % 2)
);
}

@Test
public void testDistinct() {
loop(MOCK_CYCLES,
MOCKS,
m -> m.ints().rangeClosed(1, 10).distinct().set(10).val(),
v -> assertEquals(10, v.size())
);
}

}