Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (4k points)

I've been trying to get to mock a method with vararg parameters using Mockito:

interface A {

  B b(int x, int y, C... c);

}

A a = mock(A.class);

B b = mock(B.class);

when(a.b(anyInt(), anyInt(), any(C[].class))).thenReturn(b);

assertEquals(b, a.b(1, 2));

This doesn't work, however if I do this instead:

when(a.b(anyInt(), anyInt())).thenReturn(b);

assertEquals(b, a.b(1, 2));

This works, despite that I have completely omitted the varargs argument when stubbing the method.

Any clues?

1 Answer

0 votes
by (46k points)

Mockito 1.8.1 introduced anyVararg() matcher:

when(a.b(anyInt(), anyInt(), Matchers.<String>anyVararg())).thenReturn(b);

Also see history for this: https://code.google.com/archive/p/mockito/issues/62

new syntax after deprecation:

when(a.b(anyInt(), anyInt(), ArgumentMatchers.<String>any())).thenReturn(b);

Related questions

0 votes
1 answer
0 votes
2 answers
0 votes
1 answer
0 votes
1 answer

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...