1

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)

Community
  • 1
  • 1
Chikitulfo
  • 263
  • 3
  • 7

1 Answers1

3

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))
Krzysztof Krasoń
  • 26,515
  • 16
  • 89
  • 115
  • The first one gives the same compilation error. The second one did it for me though, Thanks! I'm having trouble understanding why when(mock.addActionListener(any(Actionlistener.class))).thenAnswer([snip]); doesn't work. But if doAnswer is put first, then it works. Care to clarify? Thanks in advance!! – Chikitulfo Jul 06 '16 at 07:13