How to verify a method is called two times with mockito verify()

后端 未结 2 1970
醉梦人生
醉梦人生 2020-11-27 10:47

I want to verify if a method is called at least once through mockito verify. I used verify and it complains like this:

org.mockito.exceptions.verification.To         


        
相关标签:
2条回答
  • 2020-11-27 11:20

    Using the appropriate VerificationMode:

    import static org.mockito.Mockito.atLeast;
    import static org.mockito.Mockito.times;
    import static org.mockito.Mockito.verify;
    
    verify(mockObject, atLeast(2)).someMethod("was called at least twice");
    verify(mockObject, times(3)).someMethod("was called exactly three times");
    
    0 讨论(0)
  • 2020-11-27 11:24

    build gradle:

    testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0"
    

    code:

    interface MyCallback {
      fun someMethod(value: String)
    }
    
    class MyTestableManager(private val callback: MyCallback){
      fun perform(){
        callback.someMethod("first")
        callback.someMethod("second")
        callback.someMethod("third")
      }
    }
    

    test:

    import com.nhaarman.mockitokotlin2.times
    import com.nhaarman.mockitokotlin2.verify
    import com.nhaarman.mockitokotlin2.mock
    ...
    val callback: MyCallback = mock()
    val manager = MyTestableManager(callback)
    manager.perform()
    
    val captor: KArgumentCaptor<String> = com.nhaarman.mockitokotlin2.argumentCaptor<String>()
    
    verify(callback, times(3)).someMethod(captor.capture())
    
    assertTrue(captor.allValues[0] == "first")
    assertTrue(captor.allValues[1] == "second")
    assertTrue(captor.allValues[2] == "third")
    
    0 讨论(0)
提交回复
热议问题