1 /* 2 * Copyright (c) 2007 Mockito contributors 3 * This program is made available under the terms of the MIT License. 4 */ 5 package org.mockitousage.stubbing; 6 7 import static java.util.Arrays.asList; 8 9 import static org.junit.Assert.assertEquals; 10 import static org.junit.Assert.fail; 11 import static org.mockito.Mockito.when; 12 13 import java.util.List; 14 15 import org.junit.Test; 16 import org.mockito.AdditionalAnswers; 17 import org.mockito.Mock; 18 import org.mockito.exceptions.base.MockitoException; 19 import org.mockitousage.IMethods; 20 import org.mockitoutil.TestBase; 21 22 public class StubbingWithExtraAnswersTest extends TestBase { 23 24 @Mock private IMethods mock; 25 26 @Test shouldWorkAsStandardMockito()27 public void shouldWorkAsStandardMockito() throws Exception { 28 // when 29 List<Integer> list = asList(1, 2, 3); 30 when(mock.objectReturningMethodNoArgs()) 31 .thenAnswer(AdditionalAnswers.returnsElementsOf(list)); 32 33 // then 34 assertEquals(1, mock.objectReturningMethodNoArgs()); 35 assertEquals(2, mock.objectReturningMethodNoArgs()); 36 assertEquals(3, mock.objectReturningMethodNoArgs()); 37 // last element is returned continuously 38 assertEquals(3, mock.objectReturningMethodNoArgs()); 39 assertEquals(3, mock.objectReturningMethodNoArgs()); 40 } 41 42 @Test shouldReturnNullIfNecessary()43 public void shouldReturnNullIfNecessary() throws Exception { 44 // when 45 List<Integer> list = asList(1, null); 46 when(mock.objectReturningMethodNoArgs()) 47 .thenAnswer(AdditionalAnswers.returnsElementsOf(list)); 48 49 // then 50 assertEquals(1, mock.objectReturningMethodNoArgs()); 51 assertEquals(null, mock.objectReturningMethodNoArgs()); 52 assertEquals(null, mock.objectReturningMethodNoArgs()); 53 } 54 55 @Test shouldScreamWhenNullPassed()56 public void shouldScreamWhenNullPassed() throws Exception { 57 try { 58 // when 59 AdditionalAnswers.returnsElementsOf(null); 60 // then 61 fail(); 62 } catch (MockitoException e) { 63 } 64 } 65 } 66