由於像計數器和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());
又想一想,有一種解決方案在代碼方面並不簡單,但最好如果co UNT首先調用的是大:
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()));
不錯!感謝您的解決方案。 –