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