Last active
November 5, 2022 19:46
-
-
Save marlonklc/5e4f77a114a2396d8bf1e56653e93796 to your computer and use it in GitHub Desktop.
[Java 8] Generate many stubs for any class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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