Search code examples
mockitoargumentcaptor

With ArgumentCaptor on a function with 2 different-typed params, is there an elegant way to ignore one of those params?


Every example of ArgumentCaptor I can find focuses on these two cases:

  • function has 1 param
  • function has 2+ params of the same type

But what if the function has two params of two different types?

I have a such a function, and I only care about one of the parameters.

// (inside a @MockBean of type FooSender)
public send(Message message, SessionID session)

This is the best solution I could come up with:

// The captor that I want
ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);

// I don't care about the sessionID param,
//   but I need this captor parameter in the
//   mocked `send` call
ArgumentCaptor<SessionID> sessionIdCaptor = ArgumentCaptor.forClass(SessionID.class);

Mockito.verify(fooSender).send(messageCaptor.capture(), sessionIdCaptor.capture());
                                                        // ^^^^^ don't care!

// I have some asserts on the messageCaptor,
//   but I don't reference sessionIdCaptor any further

Is there a way to do this without constructing the sessionIdCaptor?


Solution

  • You don't need a captor, just match any():

    Mockito.verify(fooSender).send(messageCaptor.capture(), Mockito.any());
    

    or any(SessionID.class) if you do not want to match null.