如何验证一个方法用mockito verify()调用两次

ct3nt3jp  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(166)

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

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

字符串

lyr7nygr

lyr7nygr1#

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

字符串

yjghlzjz

yjghlzjz2#

对于Kotlin:

构建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 uut = MyTestableManager(callback)
uut.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")

对于Java:

Lombok用来简化。如果你愿意,你也可以键入构造函数。
构建gradle:

testImplementation "org.mockito:mockito-core:3.6.28"


代码:

// MyCallback.java
public interface MyCallback {
  void someMethod(String value);
}
// MyTestableManager.java
public class MyTestableManager {
  private MyCallback callback;

  public MyTestableManager(MyCallback callback) {
    this.callback = callback;
  }

  public void perform(){
    callback.someMethod("first");
    callback.someMethod("second");
    callback.someMethod("third");
  }
}


测试:

import org.mockito.Mockito.times;
import org.mockito.Mockito.verify;
import org.mockito.Mock;
import org.mockito.Captor;
// whatever other imports you need
@Mock
private MyCallback callback;
@Captor
private ArgumentCaptor<String> captor;

private MyTestableManager uut = new MyTestableManager(callback);

// in your test method:
uut.perform()

verify(callback, times(3)).someMethod(captor.capture())

assertTrue(captor.getAllValues().get(0) == "first")
assertTrue(captor.getAllValues().get(1) == "second")
assertTrue(captor.getAllValues().get(2) == "third")

相关问题