仅在特定代码块中验证模拟调用,从而避免其他调用

时间:2018-01-03 12:11:27

标签: java unit-testing mockito

我有这个(简化的)服务类:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://SUBDOMAIN.DOMAIN:8080/api/v1/upload. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘http://[DOMAIN-NAME].com’).

这种测试方法:

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();
    }
}

如何告诉Mockito在“安排”期间忽略@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(); } 的来电并仅在“行动”期间验证来电?我想验证eventListener.call()期间是否调用eventListener.call()并忽略所有其他调用。

1 个答案:

答案 0 :(得分:1)

在演戏前,请致电:

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

Mockito.clearInvocations(eventListener) // resets only the invocation history