如何确保方法在更改后被调用,并且在 Mockito 的另一次更改后不再调用
How to make sure a method is called after a change and not called anymore after another change in Mockito
我有一些使用 Mockito 的测试代码:
public class ProcessFunctionClass {
public void processElement(Tuple2<String, String> tuple,
Context context, Collector<Tuple2<String, String>> collector) {
// if the state is empty, start a timer
if (listState.get().iterator().hasNext() == false)
context.timerService().registerEventTimeTimer(1000);
listState.add("someStringToBeStored");
// ...
}
}
我想先调用 processElement()
,然后验证计时器 (context.timerService()
) 是否已启动,然后再次调用 processElement()
,然后验证计时器是否未启动再次。我不想使用 verify()
表示该方法已被整体调用一次;我想准确地测试我所描述的内容。我怎样才能在 Mockito 中做到这一点?
这是我的尝试:
TimerService timerService = mock(TimerService.class);
processFunctionClass.processElement(tuple1, context, collector);
verify(timerService, times(1)).registerProcessingTimeTimer(anyLong()); // this passes as expected
processFunctionClass.processElement(tuple2, context, collector);
verify(timerService, times(0)).registerProcessingTimeTimer(anyLong()); // this fails as the method was called once before
答案是改一次,验证方法被调用,第二次改,一共验证方法调用一次。看起来这是可用的最准确的描述方式。
我有一些使用 Mockito 的测试代码:
public class ProcessFunctionClass {
public void processElement(Tuple2<String, String> tuple,
Context context, Collector<Tuple2<String, String>> collector) {
// if the state is empty, start a timer
if (listState.get().iterator().hasNext() == false)
context.timerService().registerEventTimeTimer(1000);
listState.add("someStringToBeStored");
// ...
}
}
我想先调用 processElement()
,然后验证计时器 (context.timerService()
) 是否已启动,然后再次调用 processElement()
,然后验证计时器是否未启动再次。我不想使用 verify()
表示该方法已被整体调用一次;我想准确地测试我所描述的内容。我怎样才能在 Mockito 中做到这一点?
这是我的尝试:
TimerService timerService = mock(TimerService.class);
processFunctionClass.processElement(tuple1, context, collector);
verify(timerService, times(1)).registerProcessingTimeTimer(anyLong()); // this passes as expected
processFunctionClass.processElement(tuple2, context, collector);
verify(timerService, times(0)).registerProcessingTimeTimer(anyLong()); // this fails as the method was called once before
答案是改一次,验证方法被调用,第二次改,一共验证方法调用一次。看起来这是可用的最准确的描述方式。