Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Mockito- how to mock uncertain number of parameter method

Tags:

java

mockito

I try to use Mockito to mock the getDeclaredMethod() of java. but the parameter of this method is un-certain. how to mock such method?

public Method getDeclaredMethod(String name, Class... parameterTypes) throws NoSuchMethodException, SecurityException {
    throw new RuntimeException("Stub!");
}
like image 338
Jesse Avatar asked Jul 22 '19 09:07

Jesse


1 Answers

Use ArgumentMatchers.any()

Matches anything, including nulls and varargs.

Example

when(mockedObject.getDeclaredMethod(anyString(),any())).thenReturn("element");

In your case

when(mockedObject.getDeclaredMethod(anyString(), (Class<?>)any())).thenReturn("element");

And also anyVararg() but which is Deprecated. as of 2.1.0

like image 194
Deadpool Avatar answered Oct 17 '22 01:10

Deadpool