Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito - verify method is called with a specific parameter ( condition )

Tags:

java

mockito

I have in my unit test the following line

verify(MyMock).handleError(any(ICallBack.class),any(BaseError.class) );

But what I want to write is a verify that tests if the base error class (2nd parameter) has

BaseError::errorCode = 3

How do I do it?
Is it only with argument capture?
Thanks.

like image 986
Bick Avatar asked Oct 15 '25 16:10

Bick


1 Answers

Just use an appropriate matcher for the second argument. For example:

verify(MyMock).handleError(any(ICallBack.class), eq(new BaseError(3)));

assuming that this instance would be equal to any BaseError instance with this error code. You can also implement a custom ArgumentMatcher<BaseError> and implement the logic where you return true if the given instances errorCode is 3 e.g. by:

verify(MyMock).handleError(any(ICallBack.class), 
                           argThat(new ArgumentMatcher<BaseError> {
   @Override
   public boolean matches(Object baseError) {
     return ((BaseError) baseError).errorCode == 3;
   }
}));
like image 127
Rafael Winterhalter Avatar answered Oct 17 '25 05:10

Rafael Winterhalter