[英]Mockito mockingDetails.getInvocations() question
What I am trying to do is to print out the number of times that a certain method was called using Mockito.我想要做的是打印出使用 Mockito 调用某个方法的次数。
When I do the following:当我执行以下操作时:
int counter =
Mockito.mockingDetails(myDependency)
.getInvocations()
.size();
System.out.println( counter );
it prints out all the methods invoked on the mock, however, I want to print out the counter for only one specific method, so if I try,它打印出模拟上调用的所有方法,但是,我只想打印出一个特定方法的计数器,所以如果我尝试,
int counter =
Mockito.mockingDetails(myDependency.doSomething())
.getInvocations()
.size();
System.out.println( counter );
it occurs an error, saying that它发生错误,说
Argument passed to Mockito.mockingDetails() should be a mock, but is null!传递给 Mockito.mockingDetails() 的参数应该是一个模拟,但为空!
Does anyone know how to solve this problem?有谁知道如何解决这个问题? Thanks in advance!
提前致谢!
You can play with reflection:你可以玩反射:
MockingDetails mockingDetails = Mockito.mockingDetails(myDependency);
Method doSomethingMethod = mockingDetails.getMockHandler()
.getMockSettings()
.getTypeToMock()
.getMethod("doSomething"); //here you can also pass the arguments of this method
long counter = mockingDetails.getInvocations()
.stream()
.filter(invocation -> invocation.getMethod().equals(doSomethingMethod))
.count();
Note that in order to get an object of Method
class, we can't simply call myDependency.getClass().getMethod("doSomething")
because in this case getClass()
would return Mockito's wrapper class generated in runtime with its own Method
objects.请注意,为了获取
Method
类的对象,我们不能简单地调用myDependency.getClass().getMethod("doSomething")
因为在这种情况下getClass()
将返回运行时生成的 Mockito 的包装类及其自己的Method
对象. So equals
in filter would return false
later.所以过滤器中的
equals
稍后会返回false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.