javaspringmockitoargument-matcher

Mockito ArgumentMatcher any Object[]


I need an ArgumentMatcher accepting any type of values in an Object array (Object[]). TestObject:

class ObjectArrayMethod {
    public int call(Object... objects) {
        return 0;
    }
}

I tried these, where all assertEquals are failing:

    ObjectArrayMethod method = Mockito.mock(ObjectArrayMethod.class);

    Object[] arg = {"", ""};
    Mockito.when(method.call(AdditionalMatchers.aryEq(arg))).thenReturn(15);
    int actual = method.call(arg);
    assertEquals(15, actual);

    ObjectArrayMethod method = Mockito.mock(ObjectArrayMethod.class);

    Mockito.when(method.call(any(Object[].class))).thenReturn(15);
    Object[] arg = new Object[] {null, null};
    int actual = method.call(arg);
    assertEquals(15, actual);

even failing:

    ObjectArrayMethod method = Mockito.mock(ObjectArrayMethod.class);

    Object[] arg = {"", ""};
    Mockito.when(method.call(AdditionalMatchers.aryEq(arg))).thenReturn(15);
    int actual = method.call(arg);
    assertEquals(15, actual);

I wrote an own Matcher:

    protected static class ObjectArrayArgumentMatcher implements ArgumentMatcher<Object[]>, VarargMatcher {

    private static final long serialVersionUID = 3846783742617041128L;
    private final Object[] values;
    private ErrorState errorState = NO_ERROR;

    protected ObjectArrayArgumentMatcher(Object[] values) {
        this.values = values;
    }

    @Override
    public boolean matches(Object[] argument) {

        if (values == null) {
            return true;
        }

        if (argument == null) {
            return false;
        }

        return true;
    }

}

and

    protected static class ObjectArrayArgumentMatcher2 extends ObjectArrayArgumentMatcher {

    private static final long serialVersionUID = 3085412884910289910L;

    protected ObjectArrayArgumentMatcher2(Object... values) {
        super(values);
    }

    @Override
    public boolean matches(Object... argument) {
        return super.matches(argument);
    }

}

Which I initialize with null values. But I's not called.

Of cause the next step is to compare arguments.

Why is neighter matches(Object[] argument) nor matches(Object... argument) called, with args {"", ""} or even {null, null}?

What I need is an ArgumentMatcher, that works for any Object array, even with mixed types like {"String", 1, new Object()}.

The method I finally want to mock is

int org.springframework.jdbc.core.JdbcTemplate.update(String sql, Object... args) throws DataAccessException

I am using

            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>2.22.0</version>

Btw. with Version 1.10.19 my ObjectArrayArgumentMatcher worked.


Solution

  • Finally this post helped me for the solution: How to properly match varargs in Mockito

    This works:

    Mockito.when(method.call(ArgumentMatchers.<Object>any())).thenReturn(10);