3

I want to verify that the following method is called

MessageSourceAccessor.getMessage(String code, Object[] args, Locale locale)

with 10th member of args array equal to "CHF" and I don't want to check other members of this array.

So far I tried the following construction:

Object [] obj = new Object[] {anyObject(),
        anyObject(), anyObject(), anyObject(), anyObject(), anyObject(), anyObject(), anyObject(), anyObject(), "CHF", anyObject(), anyObject()};

verify(msa, times(1))
        .getMessage(eq("invoice.emailBody.1"), aryEq(obj), any(Locale.class));

Unfortunately mockito complains that I cannot use anyObject() in this case. On the other hand if I don't use it I must provide values for all of the array members which is not what I want.
Perhaps someone faced this issue before? If so, I would appreciate any help

Thanks

1 Answer 1

7

You can use an ArgumentCaptor to capture the args argument and then inspect the captured value to assert that the 10th member of args array is equal to "CHF". For example:

    msa.getMessage(code, args, aLocale);

    ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class);
    Mockito.verify(mock).getMessage(Mockito.anyString(), (Object[]) captor.capture(), Mockito.any(Locale.class));

    List<Object> actualArgs = Arrays.asList((Object[]) captor.getValue());
    Assert.assertEquals(10, actualArgs.size());
    Assert.assertEquals("CHF", actualArgs.get(9));
}
Sign up to request clarification or add additional context in comments.

1 Comment

You can now define an ArgumentCaptor<Object> which would save you from casting after capture() and getValue()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.