Mocking vs. Spying in mocking frameworks

后端 未结 7 1286
执念已碎
执念已碎 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:47

    In Mockito if you assign any object to instance variable of Mock Object then does not affect on Mock Object.

    But in case of Spy, if you assign any object to instance variable of Spy Object then does affect on Spy Object because of Spy act like real-time object modification.

    For a reference example are

    @RunWith(MockitoJUnitRunner.class)
    public class MockSpyExampleTest {
    
        @Mock
        private List mockList;
    
        @Spy
        private List spyList = new ArrayList();
    
        @Test
        public void testMockList() {
            //by default, calling the methods of mock object will do nothing
            mockList.add("test");
            assertNull(mockList.get(0));
        }
    
        @Test
        public void testSpyList() {
            //spy object will call the real method when not stub
            spyList.add("test");
            assertEquals("test", spyList.get(0));
        }
    }
    

提交回复
热议问题