使用Mockito进行部分模拟

时间:2016-02-23 06:58:04

标签: unit-testing mockito

你有一个类需要覆盖其中一个方法的行为。如何用Mockito部分模拟“大小”?

class NaughtyLinkedList extends LinkedList {
    public int size() { throw new RuntimeException("don't call me");}
}

1 个答案:

答案 0 :(得分:1)

注意:自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 docs了解背景信息。