Mockito嘲笑Details.getInvocations()问题

我想做的是打印出使用Mockito调用某种方法的次数。

当我执行以下操作时:

 int counter =
    Mockito.mockingDetails(myDependency)
        .getinvocations()
        .size();
System.out.println( counter );

它会打印出模拟程序上调用的所有方法,但是,我只想打印一种特定方法的计数器,所以如果尝试,

 int counter =
    Mockito.mockingDetails(myDependency.doSomething())
        .getinvocations()
        .size();
System.out.println( counter );

它发生错误,说

传递给Mockito.mockingDetails()的参数应该是模拟的,但为空!

有人知道如何解决这个问题吗?预先感谢!

gouridetongxingzheng 回答:Mockito嘲笑Details.getInvocations()问题

您可以进行反思:

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();

请注意,为了获取Method类的对象,我们不能简单地调用myDependency.getClass().getMethod("doSomething"),因为在这种情况下,getClass()会返回运行时生成的Mockito的包装器类,并带有自己的包装类。 Method个对象。因此,过滤器中的equals将在以后返回false

本文链接:https://www.f2er.com/2535436.html

大家都在问