1

I try to test my service with mockito 2.7.15.

First I try this:

when(customerDaoMock.find(AdditionalMatchers.not(id1))).thenReturn(null);

But I got a InvalidUseOfmatchersException.. So I googled the problem and found this stackoverflow question. After that my second try would have been:

when(customerDaoMock.find(AdditionalMatchers.not(Mockito.argThat‌(id1)))).thenReturn(null);

but Mockito class has no longer method argThat

So my question is how can I use not negation method in mockito?

Or is there any other option, or better solution for this problem?

Community
  • 1
  • 1
LakiGeri
  • 2,046
  • 6
  • 30
  • 56

2 Answers2

2

Here is an example from the AdditionalMatchers javadoc:

//anything but not "ejb"
mock.someMethod(not(eq("ejb")));

Here is working example:

public static class Tmp {
    public String f(Long a) {
        return a.toString();
    }
}

@Test
public void mockitoTest() {
    Tmp mock = Mockito.mock(Tmp.class);
    when(mock.f(AdditionalMatchers.not(Mockito.eq(5L)))).thenReturn("42");

    Assert.assertEquals("42", mock.f(4L));
    Assert.assertNull(mock.f(5L));
}
solomkinmv
  • 1,804
  • 3
  • 19
  • 30
  • Thx for the response! Unfortunataly AdditionalMatchers of mockito has no `eq` method with one parameter. (for Long) Check this: "`The method eq(double, double) in the type AdditionalMatchers is not applicable for the arguments (Long)`" – LakiGeri Mar 24 '17 at 10:35
1

Maybe it is more understandable without the static imports:

Mockito.when(customerDaoMock.find(AdditionalMatchers.not(Mockito.eq(id1))))
    .thenReturn(null);

So you can use ArgumentMatchers#eq(long) paired with AdditionalMatchers#not(long).

DVarga
  • 21,311
  • 6
  • 55
  • 60