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.matchers; 6 7 import static org.junit.Assert.assertEquals; 8 import static org.junit.Assert.fail; 9 import static org.mockito.Mockito.*; 10 11 import org.junit.Before; 12 import org.junit.Test; 13 import org.mockito.exceptions.verification.WantedButNotInvoked; 14 import org.mockitousage.IMethods; 15 import org.mockitoutil.TestBase; 16 17 public class VerificationAndStubbingUsingMatchersTest extends TestBase { 18 private IMethods one; 19 private IMethods two; 20 private IMethods three; 21 22 @Before setUp()23 public void setUp() { 24 one = mock(IMethods.class); 25 two = mock(IMethods.class); 26 three = mock(IMethods.class); 27 } 28 29 @Test shouldStubUsingMatchers()30 public void shouldStubUsingMatchers() { 31 when(one.simpleMethod(2)).thenReturn("2"); 32 when(two.simpleMethod(anyString())).thenReturn("any"); 33 when(three.simpleMethod(startsWith("test"))).thenThrow(new RuntimeException()); 34 35 assertEquals(null, one.simpleMethod(1)); 36 assertEquals("2", one.simpleMethod(2)); 37 38 assertEquals("any", two.simpleMethod("two")); 39 assertEquals("any", two.simpleMethod("two again")); 40 41 assertEquals(null, three.simpleMethod("three")); 42 assertEquals(null, three.simpleMethod("three again")); 43 44 try { 45 three.simpleMethod("test three again"); 46 fail(); 47 } catch (RuntimeException e) { 48 } 49 } 50 51 @Test shouldVerifyUsingMatchers()52 public void shouldVerifyUsingMatchers() { 53 doThrow(new RuntimeException()).when(one).oneArg(true); 54 when(three.varargsObject(5, "first arg", "second arg")).thenReturn("stubbed"); 55 56 try { 57 one.oneArg(true); 58 fail(); 59 } catch (RuntimeException e) { 60 } 61 62 one.simpleMethod(100); 63 two.simpleMethod("test Mockito"); 64 three.varargsObject(10, "first arg", "second arg"); 65 66 assertEquals("stubbed", three.varargsObject(5, "first arg", "second arg")); 67 68 verify(one).oneArg(eq(true)); 69 verify(one).simpleMethod(anyInt()); 70 verify(two).simpleMethod(startsWith("test")); 71 verify(three).varargsObject(5, "first arg", "second arg"); 72 verify(three).varargsObject(eq(10), eq("first arg"), startsWith("second")); 73 74 verifyNoMoreInteractions(one, two, three); 75 76 try { 77 verify(three).varargsObject(eq(10), eq("first arg"), startsWith("third")); 78 fail(); 79 } catch (WantedButNotInvoked e) { 80 } 81 } 82 } 83