package org.mockitousage; import java.util.*; import org.junit.*; import static org.junit.Assert.*; import org.junit.runner.*; import static org.mockito.Mockito.*; import org.mockito.runners.*; import org.mockito.*; import org.mockito.exceptions.verification.*; import org.mockito.invocation.*; import org.mockito.stubbing.*; import org.hamcrest.beans.*; /** * File created from code snippets in the official * <a href="http://mockito.googlecode.com/svn/tags/latest/javadoc/org/mockito/Mockito.html">Mockito documentation</a>, * with some minor changes. */ @SuppressWarnings({"unchecked"}) @RunWith(MockitoJUnitRunner.class) public final class JavadocExamplesTest { @Mock List<String> mockedList; @Test // Uses of Mockito API: 3 public void verifyingBehavior() { // Mock creation (for interfaces or concrete classes): MockedClass mock = mock(MockedClass.class); //using mock object mock.doSomething("one", true); mock.someMethod("test"); //verification verify(mock).doSomething("one", true); verify(mock).someMethod("test"); } @Test // Uses of Mockito API: 5 public void stubbing() { MockedClass mock = mock(MockedClass.class); //stubbing when(mock.getItem(0)).thenReturn("first"); when(mock.getItem(1)).thenThrow(new RuntimeException()); assertEquals("first", mock.getItem(0)); try { mock.getItem(1); } catch (RuntimeException e) { // OK } assertNull(mock.getItem(999)); } @Test // Uses of Mockito API: 3 public void stubbingAndVerifying() { when(mockedList.get(0)).thenReturn("first"); assertEquals("first", mockedList.get(0)); // Although it is possible to verify a stubbed invocation, usually it's just redundant. // If your code cares what get(0) returns then something else breaks (often before even // verify() gets executed). // If your code doesn't care what get(0) returns then it should not be stubbed. verify(mockedList).get(0); } @Test // Uses of Mockito API: 8 public void argumentMatchers() { //stubbing using built-in anyInt() argument matcher when(mockedList.get(anyInt())).thenReturn("element"); //stubbing using hamcrest: when(mockedList.contains(argThat(new HasProperty<String>("abc")))).thenReturn(true); assertEquals("element", mockedList.get(999)); //you can also verify using an argument matcher verify(mockedList).get(anyInt()); } @Test // Uses of Mockito API: 15 public void verifyingNumberOfInvocations() { //using mock mockedList.add("once"); mockedList.add("twice"); mockedList.add("twice"); mockedList.add("three times"); mockedList.add("three times"); mockedList.add("three times"); //following two verifications work exactly the same - times(1) is used by default verify(mockedList).add("once"); verify(mockedList, times(1)).add("once"); //exact number of invocations verification verify(mockedList, times(2)).add("twice"); verify(mockedList, times(3)).add("three times"); //verification using never(). never() is an alias to times(0) verify(mockedList, never()).add("never happened"); //verification using atLeast()/atMost() verify(mockedList, atLeastOnce()).add("three times"); verify(mockedList, atLeast(2)).add("three times"); verify(mockedList, atMost(5)).add("three times"); } @Test(expected = RuntimeException.class) // Uses of Mockito API: 2 public void stubbingVoidMethodsWithExceptions() { // "thenThrow(...)" is not applicable for void methods, so "doThrow" is used; // note also that in this situation it's "when(mock)", not "when(mock.someMethod(...))" doThrow(new RuntimeException()).when(mockedList).clear(); //following throws RuntimeException: mockedList.clear(); } @Test // Uses of Mockito API: 5 public void verificationInOrder() { List<String> firstMock = mock(List.class); List<String> secondMock = mock(List.class); //using mocks firstMock.add("was called first"); secondMock.add("was called second"); //create inOrder object passing any mocks that need to be verified in order InOrder inOrder = inOrder(firstMock, secondMock); //following will make sure that firstMock was called before secondMock inOrder.verify(firstMock).add("was called first"); inOrder.verify(secondMock).add("was called second"); } @Test // Uses of Mockito API: 6 public void verifyingThatInteractionsNeverHappened() { List<String> mockTwo = mock(List.class); List<String> mockThree = mock(List.class); //using mocks - only mockedList is interacted mockedList.add("one"); //ordinary verification verify(mockedList).add("one"); //verify that method was never called on a mock verify(mockedList, never()).add("two"); //verify that other mocks were not interacted verifyZeroInteractions(mockTwo, mockThree); } @Test(expected = NoInteractionsWanted.class) // Uses of Mockito API: 3 public void verifyingThatInteractionsNeverHappenedWhenTheyDid() { List<String> mockTwo = mock(List.class); mockedList.add("one"); mockTwo.size(); verify(mockedList).add("one"); verifyZeroInteractions(mockTwo); } @Test // Uses of Mockito API: 3 public void verifyingAllInteractions() { mockedList.add("one"); mockedList.add("two"); // Verifies first interaction: verify(mockedList).add("one"); // Verifies second (and last) interaction: verify(mockedList).add("two"); // Verify that no other interactions happened to mockedList: verifyNoMoreInteractions(mockedList); } @Test(expected = NoInteractionsWanted.class) // Uses of Mockito API: 3 public void verifyingAllInteractionsWhenMoreOfThemHappen() { mockedList.add("one"); mockedList.add("two"); mockedList.size(); verify(mockedList).add("one"); verify(mockedList).add("two"); verifyNoMoreInteractions(mockedList); } @Test // Uses of Mockito API: 4 public void stubbingConsecutiveCalls() { Iterator<String> mock = mock(Iterator.class); when(mock.next()).thenThrow(new IllegalStateException()).thenReturn("foo"); // First call: throws exception. try { mock.next(); } catch (IllegalStateException e) { // OK } // Second call: prints "foo". assertEquals("foo", mock.next()); // Any consecutive call: prints "foo" as well (last stubbing wins). assertEquals("foo", mock.next()); } @Test // Uses of Mockito API: 7 public void stubbingWithCallbacks() { final MockedClass mock = mock(MockedClass.class); when(mock.someMethod(anyString())).thenAnswer(new Answer() { public Object answer(InvocationOnMock invocation) { assertSame(mock, invocation.getMock()); Object[] args = invocation.getArguments(); return "called with arguments: " + Arrays.toString(args); } }); assertEquals("called with arguments: [foo]", mock.someMethod("foo")); } @Test // Uses of Mockito API: 9 public void spyingOnRealObjects() { MockedClass spy = spy(new MockedClass()); // Optionally, you can stub out some methods: when(spy.getSomeValue()).thenReturn(100); // When using the regular "when(spy.someMethod(...)).thenDoXyz(...)" API, all calls to a spy // object will not only perform stubbing, but also execute the real method: // when(spy.get(1)).thenReturn("an item"); would throw an IndexOutOfBoundsException. // Therefore, a different API may need to be used with a spy, in order to avoid side effects: doReturn("an item").when(spy).getItem(1); // Using the spy calls real methods, except those stubbed out: spy.doSomething("one", true); spy.doSomething("two", false); assertEquals("one", spy.getItem(0)); assertEquals("an item", spy.getItem(1)); assertEquals(100, spy.getSomeValue()); // Optionally, you can verify: verify(spy).doSomething("one", true); // the real "doSomething" method is not called here verify(spy).doSomething(eq("two"), anyBoolean()); } @Test // Uses of Mockito API: 6 public void capturingSingleArgumentForVerification() { MockedClass mock = mock(MockedClass.class); mock.doSomething(new Person("John")); mock.doSomething(new Person("Jane")); ArgumentCaptor<Person> peopleCaptor = ArgumentCaptor.forClass(Person.class); verify(mock, times(2)).doSomething(peopleCaptor.capture()); List<Person> capturedPeople = peopleCaptor.getAllValues(); assertEquals("John", capturedPeople.get(0).getName()); assertEquals("Jane", capturedPeople.get(1).getName()); } @Test // Uses of Mockito API: 8 public void capturingMultipleArgumentsForVerification() { MockedClass mock = mock(MockedClass.class); mock.doSomething("test", true); ArgumentCaptor<String> captor1 = ArgumentCaptor.forClass(String.class); ArgumentCaptor<Boolean> captor2 = ArgumentCaptor.forClass(boolean.class); verify(mock).doSomething(captor1.capture(), captor2.capture()); assertEquals("test", captor1.getValue()); assertTrue(captor2.getValue()); } @Test // Uses of Mockito API: 5 public void chainingMethodCallsWithDeepStubbing() { MockedClass mock = mock(MockedClass.class, RETURNS_DEEP_STUBS); // note that we're stubbing a chain of methods here: getBar().getName() when(mock.getPerson().getName()).thenReturn("deep"); // note that we're chaining method calls: getBar().getName() assertEquals("deep", mock.getPerson().getName()); // The following verification does work: verify(mock.getPerson()).getName(); // ... but this one does not: verify(mock).getPerson(); } }