Mockito 3 any() 严格存根参数不匹配

Iza*_*aya 6 java stub mockito

我正在使用 Mockito 3.1.0。

我正在尝试用以下语法模拟我的方法:

when(mockedObject.myMethod(any(HttpServletRequest.class)).thenReturn(1);
Run Code Online (Sandbox Code Playgroud)

myMethod很简单:

public Integer myMethod(HttpServletRequest request) {
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在我正在测试的方法中,它只是通过以下方式调用:

int r = myObject.myMethod(request);
Run Code Online (Sandbox Code Playgroud)

但我得到:

org.mockito.exceptions.misusing.PotentialStubbingProblem: 
Strict stubbing argument mismatch. Please check:
 - this invocation of 'myMethod' method:
    mockedObject.myMethod(null);
    -> at somefile.java:160)
 - has following stubbing(s) with different arguments:
    1. mockedObject.myMethod(null);
      -> at somefileTest.java:68)
Run Code Online (Sandbox Code Playgroud)

Iza*_*aya 6

如果提供的参数为 null,则此处 所解释的any(myClass)不起作用,只能any()按照此处的解释起作用。就我而言,request它为空,所以any(HttpServletRequest.class)无法捕获它。我通过改变来修复它

when(mockedObject.myMethod(any(HttpServletRequest.class)).thenReturn(1);
Run Code Online (Sandbox Code Playgroud)

如果您确定它将为空,则对此

when(mockedObject.myMethod(null)).thenReturn(1);
Run Code Online (Sandbox Code Playgroud)

或者如果您想捕获所有情况,请执行此操作

when(mockedObject.myMethod(any())).thenReturn(1);
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用ArgumentMatchers

when(mockedObject.myMethod(ArgumentMatchers.<HttpServletRequest>any())).thenReturn(1);
Run Code Online (Sandbox Code Playgroud)

感谢@xerx593 的解释。