Mockito - @Spy vs @Mock

后端 未结 7 1005
南旧
南旧 2020-11-29 17:33

Mockito - I understand a spy calls the real methods on an object, while a mock calls methods on the double object. Also spies are to be avoided unless there is a code smell.

7条回答
  •  我在风中等你
    2020-11-29 18:20

    TL;DR version,

    With mock, it creates a bare-bone shell instance for you.

    List mockList = Mockito.mock(ArrayList.class);
    

    With spy you can partially mock on an existing instance

    List spyList = Mockito.spy(new ArrayList());
    

    Typical use case for Spy: the class has a parameterized constructor, you want to create the object first.

提交回复
热议问题