Mocking vs. Spying in mocking frameworks

后端 未结 7 1295
执念已碎
执念已碎 2020-11-28 20:24

In mocking frameworks, you can mock an object or spy on it. What\'s the difference between the two and when would/should I use one over the other?

7条回答
  •  鱼传尺愫
    2020-11-28 20:53

    I'll try to explain using an 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 a nutshell, you will spy real object and stub some of the methods.

提交回复
热议问题