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