Mockito Argument Code Behavior

I ran into a problem when I need to track the call of a method, but only with the specified argument parameter. See Question below.

@Test
public void simpleTest() {
    ArgumentCaptor<Pear> captor = ArgumentCaptor.forClass(Pear.class);
    Action action = mock(Action.class);
    action.perform(new Pear());
    action.perform(new Apple());
    verify(action, times(1)).perform(captor.capture());
}

static class Action {

    public void perform(IFruit fruit) {}

}
static class Pear implements IFruit {}
static class Apple implements IFruit {}

interface IFruit {}

But getting:

org.mockito.exceptions.verification.TooManyActualInvocations: 
action.perform(<Capturing argument>);
Wanted 1 time:
But was 2 times. Undesired invocation:
..

What am I doing wrong? Mockito v 1.10

Honestly, it's simple, and my code is more complex, and I don't know how many times the execution will be called using Apple.class. It's not important for me. I need to check only the execution call (Pear.class)

UPD: , Pear.class . , - , - (DomainObject). , save (MyDomainObject) , , . , reset mock

+4
3

Pear , :

verify(action, times(1)).perform(isA(Pear.class));

Cf. . paticular

, Mockito 2.1 :

verify(action, times(1)).perform(any(Pear.class));

. public static T any ( )

... : isA ()...

... mockito 2.1.0 any() anyObject() .

+2

  @Test
  public void simpleTest() {
    MyArgumentCaptor pearCaptor = new MyArgumentCaptor(Pear.class);
    Action action = mock(Action.class);

    action.perform(new Pear());
    action.perform(new Apple());

    verify(action, times(1)).perform((IFruit) argThat(pearCaptor));

    System.out.println(pearCaptor.getMatchedObj());
  }


  class MyArgumentCaptor extends InstanceOf {
    private Object matchedObj;

    MyArgumentCaptor(Class<?> clazz) {
      super(clazz);
    }

    @Override
    public boolean matches(Object actual) {
      boolean matches = super.matches(actual);
      if (matches) {
        matchedObj = actual;
      }
      return matches;
    }

    Object getMatchedObj() {
      return matchedObj;
    }
  }
+2

You call the action twice, but expect one call ( times(1)). Try using times(2)if it is called twice or omits it if you don't care how many times you call it.

action.perform(new Pear());
action.perform(new Apple());
0
source

Source: https://habr.com/ru/post/1692420/


All Articles