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.TooManyActualInvocations; 12 import org.mockito.exceptions.verification.WantedButNotInvoked; 13 import org.mockitousage.IMethods; 14 import org.mockitoutil.TestBase; 15 16 import java.util.List; 17 18 import static junit.framework.TestCase.fail; 19 import static org.mockito.Mockito.*; 20 21 public class BasicVerificationTest extends TestBase { 22 23 @Mock private List<String> mock; 24 @Mock private List<String> mockTwo; 25 26 @Test shouldVerify()27 public void shouldVerify() throws Exception { 28 mock.clear(); 29 verify(mock).clear(); 30 31 mock.add("test"); 32 verify(mock).add("test"); 33 34 verifyNoMoreInteractions(mock); 35 } 36 37 @Test(expected=WantedButNotInvoked.class) shouldFailVerification()38 public void shouldFailVerification() throws Exception { 39 verify(mock).clear(); 40 } 41 42 @Test shouldFailVerificationOnMethodArgument()43 public void shouldFailVerificationOnMethodArgument() throws Exception { 44 mock.clear(); 45 mock.add("foo"); 46 47 verify(mock).clear(); 48 try { 49 verify(mock).add("bar"); 50 fail(); 51 } catch (AssertionError expected) {} 52 } 53 54 @Test shouldFailOnWrongMethod()55 public void shouldFailOnWrongMethod() throws Exception { 56 mock.clear(); 57 mock.clear(); 58 59 mockTwo.add("add"); 60 61 verify(mock, atLeastOnce()).clear(); 62 verify(mockTwo, atLeastOnce()).add("add"); 63 try { 64 verify(mockTwo, atLeastOnce()).add("foo"); 65 fail(); 66 } catch (WantedButNotInvoked e) {} 67 } 68 69 @Test shouldDetectRedundantInvocation()70 public void shouldDetectRedundantInvocation() throws Exception { 71 mock.clear(); 72 mock.add("foo"); 73 mock.add("bar"); 74 75 verify(mock).clear(); 76 verify(mock).add("foo"); 77 78 try { 79 verifyNoMoreInteractions(mock); 80 fail(); 81 } catch (NoInteractionsWanted e) {} 82 } 83 84 @Test shouldDetectWhenInvokedMoreThanOnce()85 public void shouldDetectWhenInvokedMoreThanOnce() throws Exception { 86 mock.add("foo"); 87 mock.clear(); 88 mock.clear(); 89 90 verify(mock).add("foo"); 91 92 try { 93 verify(mock).clear(); 94 fail(); 95 } catch (TooManyActualInvocations e) {} 96 } 97 98 @Test shouldVerifyStubbedMethods()99 public void shouldVerifyStubbedMethods() throws Exception { 100 when(mock.add("test")).thenReturn(Boolean.FALSE); 101 102 mock.add("test"); 103 104 verify(mock).add("test"); 105 } 106 107 108 @Test shouldDetectWhenOverloadedMethodCalled()109 public void shouldDetectWhenOverloadedMethodCalled() throws Exception { 110 IMethods mockThree = mock(IMethods.class); 111 112 mockThree.varargs((Object[]) new Object[] {}); 113 try { 114 verify(mockThree).varargs((String[]) new String[] {}); 115 fail(); 116 } catch(WantedButNotInvoked e) {} 117 } 118 } 119