简体   繁体   中英

Mockito - Match any instance implementing an interface, and answer

Mocking a class that at some point is called to add an instance of ActionListener (the interface in java.awt.event) with signature

public void addActionListener(ActionListener l).

Trying to mock the method call to use an answer, so that I can keep track of its ActionListeners, when it is called with anonymously created instances of ActionListener (just like in this answer ). But I am unable to make it accept any instance of interface ActionListener.

So far I have tried several examples from other questions, to no avail:

when(mock.addActionListener(Matchers.<ActionListener>any())).thenAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            Object[] arguments = invocation.getArguments();
            if (arguments != null && arguments.length > 0 && arguments[0] != null) {
                listeners.add((ActionListener) arguments[0]);
            }
            return null;
        }
    });
when(mock.addActionListener(any(ActionListener.class))).thenAnswer([..snip..]);

All of them give compilation errors saying Cannot resolve method when(void) .

Is there any way to make Matchers.any match against any instance that implements the interface, and use it for the answer? Is it not possible because its return value is void?

Using Mockito 1.10, powermock 1.6.5 and java 7. (I can't use Java 8)

You can use Mockito.doAnswer() , it is created for methods returning void :

doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocation) throws Throwable {
        Object[] arguments = invocation.getArguments();
        if (arguments != null && arguments.length > 0 && arguments[0] != null) {
            listeners.add((ActionListener) arguments[0]);
        }
        return null;
    }
}).when(mock).addActionListener(Matchers.<ActionListener>any());
doAnswer([..snip..]).when(mock).addActionListener(any(ActionListener.class))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM