• 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.verification;
7 
8 import org.junit.Test;
9 import org.mockito.Mock;
10 import org.mockito.exceptions.verification.NoInteractionsWanted;
11 import org.mockito.exceptions.verification.WantedButNotInvoked;
12 import org.mockitoutil.TestBase;
13 
14 import java.util.List;
15 
16 import static org.junit.Assert.fail;
17 import static org.mockito.Matchers.anyInt;
18 import static org.mockito.Mockito.only;
19 import static org.mockito.Mockito.verify;
20 
21 public class OnlyVerificationTest extends TestBase {
22 
23     @Mock private List<Object> mock;
24 
25     @Mock private List<Object> mock2;
26 
27     @Test
shouldVerifyMethodWasInvokedExclusively()28     public void shouldVerifyMethodWasInvokedExclusively() {
29         mock.clear();
30         verify(mock, only()).clear();
31     }
32 
33     @Test
shouldVerifyMethodWasInvokedExclusivelyWithMatchersUsage()34     public void shouldVerifyMethodWasInvokedExclusivelyWithMatchersUsage() {
35         mock.get(0);
36         verify(mock, only()).get(anyInt());
37     }
38 
39     @Test
shouldFailIfMethodWasNotInvoked()40     public void shouldFailIfMethodWasNotInvoked() {
41         mock.clear();
42         try {
43             verify(mock, only()).get(0);
44             fail();
45         } catch (WantedButNotInvoked e) {}
46     }
47 
48     @Test
shouldFailIfMethodWasInvokedMoreThanOnce()49     public void shouldFailIfMethodWasInvokedMoreThanOnce() {
50         mock.clear();
51         mock.clear();
52         try {
53             verify(mock, only()).clear();
54             fail();
55         } catch (NoInteractionsWanted e) {}
56     }
57 
58     @Test
shouldFailIfMethodWasInvokedButWithDifferentArguments()59     public void shouldFailIfMethodWasInvokedButWithDifferentArguments() {
60         mock.get(0);
61         mock.get(2);
62         try {
63             verify(mock, only()).get(999);
64             fail();
65         } catch (WantedButNotInvoked e) {}
66     }
67 
68     @Test
shouldFailIfExtraMethodWithDifferentArgsFound()69     public void shouldFailIfExtraMethodWithDifferentArgsFound() {
70         mock.get(0);
71         mock.get(2);
72         try {
73             verify(mock, only()).get(2);
74             fail();
75         } catch (NoInteractionsWanted e) {}
76     }
77 
78     @Test
shouldVerifyMethodWasInvokedExclusivelyWhenTwoMocksInUse()79     public void shouldVerifyMethodWasInvokedExclusivelyWhenTwoMocksInUse() {
80         mock.clear();
81         mock2.get(0);
82         verify(mock, only()).clear();
83         verify(mock2, only()).get(0);
84     }
85 
86 }
87