mockito.verify
时间: 2023-09-18 19:13:55 浏览: 77
`Mockito.verify()`是用于验证Mock对象的方法。它可以检查Mock对象是否按照预期调用了特定的方法。例如,如果我们想验证一个名为`myMockObject`的Mock对象是否调用了`myMethod()`方法,则可以使用以下代码:
```
Mockito.verify(myMockObject).myMethod();
```
如果`myMethod()`方法从未被调用,或者参数与预期不符,则会抛出`VerificationError`异常。
相关问题
mockito.spy
Mockito.spy() 是一个用于创建一个对象的Spy的Mockito方法。Spy是一个特殊的Mock对象,它可以部分地模拟真实对象,并且可以记录和验证方法的调用。与普通的Mock对象不同,Spy对象可以保留真实对象的部分行为,只有在需要时才会模拟特定的行为。
使用Mockito.spy()方法,您可以将一个真实的对象包装成一个Spy对象。下面是一个示例:
```java
List<String> list = new ArrayList<>();
List<String> spyList = Mockito.spy(list);
// 对Spy对象的部分行为进行模拟
Mockito.when(spyList.size()).thenReturn(10);
// 调用真实对象的方法
spyList.add("Hello");
spyList.add("World");
// 验证Spy对象的方法调用
Mockito.verify(spyList).add("Hello");
Mockito.verify(spyList).add("World");
```
在上面的示例中,我们将一个ArrayList对象包装成了一个Spy对象。然后,我们使用`when()`方法模拟了`size()`方法的返回值为10。接下来,我们调用了真实对象的`add()`方法,并且验证了这两个方法的调用。
需要注意的是,Spy对象会保留真实对象的部分行为。未被模拟的方法调用将会调用真实对象的对应方法,并返回真实的结果。因此,在使用Spy对象时要小心处理未被模拟的方法,以避免产生意外的行为。
希望这个回答能够帮助到您!如果您有任何其他问题,请随时提问。
Mockito.doReturn
Mockito.doReturn() is a method in the Mockito library that allows you to specify a return value for a method call on a mock object. It is used to stub a method call on a mock object to return a specific value, rather than executing the actual method code.
Here is an example of how to use Mockito.doReturn():
```
// Create a mock object of a class
SomeClass myMock = Mockito.mock(SomeClass.class);
// Stub the method call to return a specific value
Mockito.doReturn("hello").when(myMock).someMethod();
// Call the method on the mock object
String result = myMock.someMethod();
// Verify that the method was called and returned the correct value
assertEquals("hello", result);
```
In this example, we create a mock object of the SomeClass class and then use Mockito.doReturn() to stub the someMethod() method to return the string "hello". When we call someMethod() on the mock object, it will return "hello" instead of executing the actual method code. We then verify that the method was called and returned the correct value using the assertEquals() method.