Mockito matcher and array of primitives

后端 未结 8 1184
既然无缘
既然无缘 2021-01-30 05:53

With Mockito, I want to verify() a method call with byte[] in its argument list, but I didn\'t find how to write this.

 myMethod( byte[         


        
相关标签:
8条回答
  • 2021-01-30 06:24

    I agree with Mutanos and Alecio. Further, one can check as many identical method calls as possible (verifying the subsequent calls in the production code, the order of the verify's does not matter). Here is the code:

    import static org.mockito.AdditionalMatchers.*;
    
        verify(mockObject).myMethod(aryEq(new byte[] { 0 }));
        verify(mockObject).myMethod(aryEq(new byte[] { 1, 2 }));
    
    0 讨论(0)
  • 2021-01-30 06:29

    I would try any(byte[].class)

    0 讨论(0)
  • You can always create a custom Matcher using argThat

    Mockito.verify(yourMockHere).methodCallToBeVerifiedOnYourMockHere(ArgumentMatchers.argThat(new ArgumentMatcher<Object>() {
        @Override
        public boolean matches(Object argument) {
            YourTypeHere[] yourArray = (YourTypeHere[]) argument;
            // Do whatever you like, here is an example:
            if (!yourArray[0].getStringValue().equals("first_arr_val")) {
                return false;
            }
            return true;
        }
    }));
    
    0 讨论(0)
  • 2021-01-30 06:32

    What works for me was org.mockito.ArgumentMatchers.isA

    for example:

    isA(long[].class)
    

    that works fine.

    the implementation difference of each other is:

    public static <T> T any(Class<T> type) {
        reportMatcher(new VarArgAware(type, "<any " + type.getCanonicalName() + ">"));
        return Primitives.defaultValue(type);
    }
    
    public static <T> T isA(Class<T> type) {
        reportMatcher(new InstanceOf(type));
        return Primitives.defaultValue(type);
    }
    
    0 讨论(0)
  • 2021-01-30 06:33

    I used Matchers.refEq for this.

    0 讨论(0)
  • 2021-01-30 06:34

    Try this:

    AdditionalMatchers.aryEq(array);
    
    0 讨论(0)
提交回复
热议问题