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