你有一个类,你需要重写它的一个方法的行为。 如何用Mockito部分模拟"大小"?
class NaughtyLinkedList extends LinkedList {
public int size() { throw new RuntimeException("don't call me");}
}
注意:从 Mockito 1.8 开始,您可以进行适当的部分模拟。注意:注释掉的行不起作用,因为"when"API 执行一次它的参数注意:所有未显式存根的调用都将调用真实对象的方法。
import org.mockito.Mockito;
...
@Test
public void partialMockWithMock(){
List mock = Mockito.mock(NaughtyLinkedList.class, Mockito.CALLS_REAL_METHODS);
mock.add(new Object()); // this calls the real function
//Mockito.when(mock.size()).thenReturn(2); // This lines throws the RuntimeException because it actually executes it's argument.
Mockito.doReturn(2).when(mock).size();
assertEquals(2,mock.size());
}
@Test
public void partialMockWithSpy() {
List list = new NaughtyLinkedList();
List spy = Mockito.spy(list);
// optionally, you can stub out some methods:
//Mockito.when(spy.size()).thenReturn(2); //Can't use "when" API, as it will execute it's argument once.
Mockito.doReturn(2).when(spy).size();
assertEquals(2,spy.size());
}
有关背景,请参阅 Mockito 文档。