Java 代码之自制 mock

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.function.BiConsumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.LongStream;

/**
* mock 数据.
*
* @author glett
*/
public class MockUtil {

private static class SingletonHolder {
private static MockUtil instance = new MockUtil();
}

public static MockUtil getInstance() {
return SingletonHolder.instance;
}

private static final int COUNT = 5;

private static String one() {
List<Integer> pool = new ArrayList<>();
IntStream.rangeClosed('0', '9').forEach(pool::add);
IntStream.rangeClosed('a', 'z').forEach(pool::add);

return new Random().ints(10, 0, pool.size()).mapToObj(e -> {
int i = (int)pool.get(e);
return String.valueOf(((char)i));
}).collect(Collectors.joining());
}

public List<String> getListStr() {
return IntStream.rangeClosed(0, COUNT).mapToObj(e -> {
return one();
}).collect(Collectors.toList());
}

public String getStr() {
return one();
}

public <T, U> List<T> getListObject(Supplier<T> ins, List<BiConsumer<T, U>> cons, U u) {
return LongStream.rangeClosed(0, COUNT).mapToObj(e -> {
T t = ins.get();
cons.forEach(con -> con.accept(t, u));
return t;
}).collect(Collectors.toList());
}

public <T, U2> List<T> getListObject(Supplier<T> instance, BiConsumer<T, Long> m, BiConsumer<T, U2> m2, U2 v2) {
return LongStream.rangeClosed(0, 10).mapToObj(e -> {
T t = instance.get();
m.accept(t, e);
m2.accept(t, v2);
return t;
}).collect(Collectors.toList());
}

public <T, U1, U2> T getObject(Supplier<T> instance, BiConsumer<T, U1> m1, U1 v1, BiConsumer<T, U2> m2, U2 v2) {
T t = instance.get();
m1.accept(t, v1);
m2.accept(t, v2);
return t;
}

public static <T, U> T getObject(Supplier<T> instance, List<BiConsumer<T, U>> list1, List<U> list2) {
int l1 = list1.size();
int l2 = list2.size();
if (l1 != l2) {
return null;
}
T t = instance.get();
IntStream.range(0, l1).forEach(i -> {
list1.get(i).accept(t, list2.get(i));
});
return t;
}
}