Mocking vs. Spying in mocking frameworks

倾然丶 夕夏残阳落幕 提交于 2019-11-27 17:07:20

Mock object replace mocked class entirely, returning recorded or default values. You can create mock out of "thin air". This is what is mostly used during unit testing.

When spying, you take an existing object and "replace" only some methods. This is useful when you have a huge class and only want to mock certain methods (partial mocking). Let me quote Mockito documentation:

You can create spies of real objects. When you use the spy then the real methods are called (unless a method was stubbed).

Real spies should be used carefully and occasionally, for example when dealing with legacy code.

When in doubt, use mocks.

Mockito warns that partial mocking isnt a good practice and you should revise your OO architecture. Spy (or partial mocking) is recomended to test legacy code.

Can try to explain using example here.

// difference between mocking, stubbing and spying
@Test
public void differenceBetweenMockingSpyingAndStubbing(){
    List list = new ArrayList();
    list.add("abc");
    assertEquals(1,list.size());
    List mockedList = spy(list);
    when(mockedList.size()).thenReturn(10);
    assertEquals(10,mockedList.size());
}

Here, we had initial real object list, in which we added one element and expected size to be one.

we spy real object meaning that we can instruct which method to be stubbed. so we declared that we stubbed method - size() on spy object which will return 10, no matter what is actual size.

in nutshell, you will spy real-object and stub some of the methods.

Spies have two definitions. One, is where the real method is called, another where, no functionality is called and only null or null equivalent values are returned, but methods were called, and they're state was recorded, commonly like, method x was called y times.

Reference: http://javapointers.com/tutorial/difference-between-spy-and-mock-in-mockito/

When using mock objects, the default behavior of the method when not stub is do nothing. Simple means, if its a void method, then it will do nothing when you call the method or if its a method with a return then it may return null, empty or the default value.

While in spy objects, of course, since it is a real method, when you are not stubbing the method, then it will call the real method behavior. If you want to change and mock the method, then you need to stub it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!