Skip to content

Instantly share code, notes, and snippets.

@marlonklc
Last active November 5, 2022 19:46
Show Gist options
  • Save marlonklc/5e4f77a114a2396d8bf1e56653e93796 to your computer and use it in GitHub Desktop.
Save marlonklc/5e4f77a114a2396d8bf1e56653e93796 to your computer and use it in GitHub Desktop.
[Java 8] Generate many stubs for any class
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Product {
private final long id;
private final String description;
private Product(long id, String description) {
this.id = id;
this.description = description;
}
private static Product of(long id, String description) {
return new Product(id, description);
}
public static Product notebook() {
return Product.of(1, "Phone");
}
public static Product mouse() {
return Product.of(2, "Notebook");
}
public static Product keyboard() {
return Product.of(3, "Notebook");
}
public static List<Product> many(int size, Supplier<Product> method) {
return IntStream.range(1, ++size)
.mapToObj(x -> method.get())
.collect(Collectors.toList());
}
}
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class Test {
@Test
public static void generate() {
List<Product> products = Stream.of(
Product.many(5, Product::keyboard),
Product.many(4, Product::mouse)
)
.flatMap(List::stream)
.collect(Collectors.toList());
assertEquals(9, products.size());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment