Mockito: How to verify a method was called only once with exact parameters ignoring calls to other methods?

前端 未结 3 663
天涯浪人
天涯浪人 2020-12-28 12:15

Using Mockito in Java how to verify a method was called only once with exact parameters ignoring calls to other methods?

Sample code:

public class Mo         


        
相关标签:
3条回答
  • 2020-12-28 12:43

    For anyone who's looking for mocking and verifying static method in Junit 5/Jupiter with Mockito, have a glance of this nice one https://stackoverflow.com/a/63242611/4809938

    0 讨论(0)
  • 2020-12-28 12:52
    Mockito.verify(foo, Mockito.times(1)).add("1");
    Mockito.verify(foo, Mockito.times(1)).add(Mockito.anyString());
    

    The first verify checks the expected parametrized call and the second verify checks that there was only one call to add at all.

    0 讨论(0)
  • 2020-12-28 13:00

    The previous answer can be simplified even further.

    Mockito.verify(foo).add("1");
    Mockito.verify(foo).add(Mockito.anyString());
    

    The single parameter verify method is just an alias to the times(1)implementation.

    0 讨论(0)
提交回复
热议问题