What is the difference between mocking and spying when using Mockito? Ask Question

What is the difference between mocking and spying when using Mockito? Ask Question

What would be a use case for a use of a Mockito spy?

It seems to me that every spy use case can be handled with a mock, using callRealMethod.

One difference I can see is if you want most method calls to be real, it saves some lines of code to use a mock vs. a spy. Is that it or am I missing the bigger picture?

ベストアンサー1

Difference between a Spy and a Mock

When Mockito creates a mock – it does so from the Class of a Type, not from an actual instance. The mock simply creates a bare-bones shell instance of the Class, entirely instrumented to track interactions with it. On the other hand, the spy will wrap an existing instance. It will still behave in the same way as the normal instance – the only difference is that it will also be instrumented to track all the interactions with it.

In the following example – we create a mock of the ArrayList class:

@Test
public void whenCreateMock_thenCreated() {
    List mockedList = Mockito.mock(ArrayList.class);

    mockedList.add("one");
    Mockito.verify(mockedList).add("one");

    assertEquals(0, mockedList.size());
}

As you can see – adding an element into the mocked list doesn’t actually add anything – it just calls the method with no other side-effect. A spy on the other hand will behave differently – it will actually call the real implementation of the add method and add the element to the underlying list:

@Test
public void whenCreateSpy_thenCreate() {
    List spyList = Mockito.spy(new ArrayList());
    spyList.add("one");
    Mockito.verify(spyList).add("one");

    assertEquals(1, spyList.size());
}

ここでは、size() メソッドを呼び出すとサイズが 1 になるが、この size() メソッドはモック化されていないため、オブジェクトの実際の内部メソッドが呼び出されたことは間違いありません。では、1 はどこから来るのでしょうか?size() はモック化 (またはスタブ化) されていないため、内部の実際の size() メソッドが呼び出され、したがってエントリが実際のオブジェクトに追加されたと言えます。

ソース:http://www.baeldung.com/mockito-spy+ 自分メモ。

おすすめ記事