Tomasz Nurkiewicz的回答似乎并没有说出全部的故事!
NB模仿版本:1.10.19。
我是一个非常多的Mockito新手,所以不能解释以下行为:如果有一个专家在那里谁可以改善这个答案,请随意。
这里讨论的方法getContentStringValue不是最终的,也不是静态的。
这一行调用了原始方法getContentStringValue:
doReturn( "dummy" ).when( im ).getContentStringValue( anyInt(), isA( ScoreDoc.class ));
这一行不调用原始方法getContentStringValue:
doReturn( "dummy" ).when( im ).getContentStringValue( anyInt(), any( ScoreDoc.class ));
由于我无法回答的原因,使用isA()会导致预期的(?)doReturn的“不调用方法”行为失败。
Let's look at the method signatures involved here: they are both static methods of Matchers. Both are said by the Javadoc to return null, which is a little difficult to get your head around in itself. Presumably the Class object passed as the parameter is examined but the result either never calculated or discarded. Given that null can stand for any class and that you are hoping for the mocked method not to be called, couldn't the signatures of isA( ... ) and any( ... ) just return null rather than a generic parameter* <T>?
无论如何:
public static <T> T isA(java.lang.Class<T> clazz)
public static <T> T any(java.lang.Class<T> clazz)
The API documentation does not give any clue about this. It also seems to say the need for such "do not call method" behaviour is "very rare". Personally I use this technique all the time: typically I find that mocking involves a few lines which "set the scene" ... followed by calling a method which then "plays out" the scene in the mock context which you have staged... and while you are setting up the scenery and the props the last thing you want is for the actors to enter stage left and start acting their hearts out...
但这远远超出了我的职权范围…我请路过的Mockito大祭司解释一下…
*“通用参数”是正确的术语吗?