// as you see, load and clear verify(mockedList, atLeastOnce()).add("one"); verify(mockedList, times(1)).add("two"); verify(mockedList, times(3)).add("three times"); verify(mockedList, never()).isEmpty(); }
@Test publicvoidcreateMockObject(){ List mockedList = mock(List.class); assertTrue(mockedList instanceof List);
@Test publicvoidconfigMockObject(){ List mockedList = mock(List.class);
// CONFIG: when calling mockedList.add("one"), return true when(mockedList.add("one")).thenReturn(true);
// CONFIG: when calling mockedList.size(), return 1 when(mockedList.size()).thenReturn(1);
assertTrue(mockedList.add("one")); // Because there's no config for mockedList.add("two"), false is // returned as default value assertFalse(mockedList.add("two")); assertEquals(mockedList.size(), 1);
Iterator i = mock(Iterator.class);
// CONFIG: when calling i.next(), return "Hello," at 1st time, // return "Mockito" at 2nd time when(i.next()).thenReturn("Hello,").thenReturn("Mockito!"); String result = i.next() + " " + i.next(); assertEquals("Hello, Mockito!", result); }
// CONFIG: throw exception when calling i.next() for the 3rd time, // which means only 2 elements in i. doThrow(new NoSuchElementException()).when(i).next(); i.next(); // now it is the 3rd time to call i.next() } }