Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify mock invocation only in specific code block, igoring other calls

I have this (simplified) service class:

public interface EventListener {

    void call();
}

public class MyService {

    private final EventListener eventListener;

    private final List<String> elements = new LinkedList<>();

    public MyService(EventListener eventListener) {
        this.eventListener = eventListener;
    }

    public void addElement(String element) {
        elements.add(element);
        eventListener.call();
    }

    public void removeElement(String element) {
        elements.remove(element);
        eventListener.call();
    }
}

And this test method:

@Test
public void remove_should_call_event_listener() {
    // arrange
    EventListener eventListener = Mockito.mock(EventListener.class);
    MyService myService = new MyService(eventListener);
    myService.addElement("dummy");

    // act
    myService.removeElement("dummy");

    // assert
    Mockito.verify(eventListener).call();
}

How can I tell Mockito to ignore calls of eventListener.call() during "arrange" and verify only calls during "act"? I want to verify that eventListener.call() was called during myService.removeElement(...) and ignore all other calls.

like image 768
Roland Weisleder Avatar asked Nov 29 '25 07:11

Roland Weisleder


1 Answers

Just before acting, call:

Mockito.reset(eventListener); // resets the set-up also

or

Mockito.clearInvocations(eventListener) // resets only the invocation history
like image 184
Maciej Kowalski Avatar answered Dec 01 '25 20:12

Maciej Kowalski