mardi 23 juin 2020

How to make sure a method is called after a change and not called anymore after another change in Mockito

I have some test code using 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");

        // ...
    }
}

I want to call the processElement() first, then verify that the timer (context.timerService()) was started, then call processElement() again, and then verify that the timer was NOT started again. I don't want to use verify() saying the method has been called once overall; I want to test for exactly what I described. How can I do that in Mockito?

Here is my attempt:

    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

Aucun commentaire:

Enregistrer un commentaire