Search code examples
javaunit-testingjunitmockito

Mockito Nullable ArgumentCaptor Value


Is it possible to have a nullable ArgumentCaptor?

I'm trying to use the below method

    public Win getWin() {
        ArgumentCaptor<Win> winCaptor = ArgumentCaptor
                .forClass(Win.class);
        Mockito.verify(producer, Mockito.atMostOnce()).accept(winCaptor.capture());
        return winCaptor.getValue();
    }

this works fine when producer.accept(win) is called but I'd like it to return null if it's not. Is this possible?

I'm currently getting this error

No argument value was captured!
You might have forgotten to use argument.capture() in verify()...
...or you used capture() in stubbing but stubbed method was not called.
Be aware that it is recommended to use capture() only with verify()

Solution

  • You can use winCaptor.getAllValues() method. It will not throw an exception if the accept() method was not called. Instead, it will return an empty list.