由于像计数器这样的可变状态和 Java 8 的 lambda 表达式不能很好地协同工作,因此没有直接的、Java 8 特定的计数器解决方案。并且每一次尝试找到一个聪明的解决方法都会比下面的无反解决方案更糟糕
public static <T> OngoingStubbing<T> switchAfter(
OngoingStubbing<T> stub, int calls, Supplier<T> first, Supplier<T> then) {
Answer<T> a1=x -> first.get(), a2=x -> then.get();
while(calls-->0) stub=stub.then(a1);
return stub.then(a2);
}
相当于使用
Mockito.when(mock.doSomething()).then(x -> method1()).then(x -> method1())
.then(x -> method1()).then(x -> method1()).then(x -> method1()).then(x -> method1())
.then(x -> method1()).then(x -> method1()).then(x -> method1()).then(x -> method1())
.then(x -> method2());
用作
switchAfter(Mockito.when(mock.doSomething()), 10, () -> method1(), () -> method2());
再想一想,有一个解决方案,在代码方面并不简单,但如果第一次调用的次数很大,则更可取:
public static <T> Answer<T> switchAfter(int calls, Supplier<T> first, Supplier<T> then) {
Iterator<T> it=Stream.concat(
IntStream.range(0, calls).mapToObj(i -> first.get()),
Stream.generate(then))
.iterator();
return x -> it.next();
}
可用作
Mockito.when(mock.doSomething()).then(switchAfter(10, () -> method1(), () -> method2()));