如何使用mockito verify()调用方法被调用两次

时间:2013-02-15 07:23:16

标签: junit mockito verify

我想通过mockito验证验证方法是否至少被调用一次。我使用验证,它抱怨这样:

org.mockito.exceptions.verification.TooManyActualInvocations: 
Wanted 1 time:
But was 2 times. Undesired invocation:

2 个答案:

答案 0 :(得分:424)

使用适当的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");

答案 1 :(得分:0)

构建gradle:

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

代码:

interface MyCallback {
  fun someMethod(value: String)
}

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

测试:

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")