简体   繁体   中英

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

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.

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 eg by:

verify(MyMock).handleError(any(ICallBack.class), 
                           argThat(new ArgumentMatcher<BaseError> {
   @Override
   public boolean matches(Object baseError) {
     return ((BaseError) baseError).errorCode == 3;
   }
}));

The following should help

     doAnswer(new Answer<Void>() {
            public Void answer(InvocationOnMock invocation) {
                Object[] args = invocation.getArguments()
                assertTrue((long)args[1], 3);
                return null;
            }
        }).when(MyMock).handleError(any(ICallBack.class),any(BaseError.class) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM