Java Mockito-如何模拟不确定数量的参数方法

Jes*_*sse 5 java mockito

我尝试使用Mockito模拟getDeclaredMethod()Java。但是此方法的参数不确定。如何嘲笑这种方法?

public Method getDeclaredMethod(String name, Class... parameterTypes) throws NoSuchMethodException, SecurityException {
    throw new RuntimeException("Stub!");
}
Run Code Online (Sandbox Code Playgroud)

Dea*_*ool 4

使用ArgumentMatchers.any()

匹配任何内容,包括 null 和 varargs。

例子

when(mockedObject.getDeclaredMethod(anyString(),any())).thenReturn("element");
Run Code Online (Sandbox Code Playgroud)

在你的情况下

when(mockedObject.getDeclaredMethod(anyString(), (Class<?>)any())).thenReturn("element");
Run Code Online (Sandbox Code Playgroud)

还有anyVararg(),但已弃用。自 2.1.0 起