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.Before; 9 import org.junit.Test; 10 import org.mockito.InOrder; 11 import org.mockito.exceptions.verification.VerificationInOrderFailure; 12 import org.mockito.exceptions.verification.WantedButNotInvoked; 13 import org.mockitousage.IMethods; 14 import org.mockitoutil.TestBase; 15 16 import static org.junit.Assert.fail; 17 import static org.assertj.core.api.Assertions.assertThat; 18 import static org.mockito.Mockito.*; 19 20 public class VerificationInOrderTest extends TestBase { 21 22 private IMethods mockOne; 23 private IMethods mockTwo; 24 private IMethods mockThree; 25 private InOrder inOrder; 26 27 @Before 28 public void setUp() { 29 mockOne = mock(IMethods.class); 30 mockTwo = mock(IMethods.class); 31 mockThree = mock(IMethods.class); 32 33 inOrder = inOrder(mockOne, mockTwo, mockThree); 34 } 35 36 @Test 37 public void shouldVerifySingleMockInOrderAndNotInOrder() { 38 mockOne = mock(IMethods.class); 39 inOrder = inOrder(mockOne); 40 41 mockOne.simpleMethod(1); 42 mockOne.simpleMethod(2); 43 44 verify(mockOne).simpleMethod(2); 45 verify(mockOne).simpleMethod(1); 46 47 inOrder.verify(mockOne).simpleMethod(2); 48 try { 49 inOrder.verify(mockOne).simpleMethod(1); 50 fail(); 51 } catch (VerificationInOrderFailure e) {} 52 } 53 54 @Test 55 public void shouldMessagesPointToProperMethod() { 56 mockTwo.differentMethod(); 57 mockOne.simpleMethod(); 58 59 try { 60 inOrder.verify(mockOne, atLeastOnce()).differentMethod(); 61 fail(); 62 } catch (WantedButNotInvoked e) { 63 assertThat(e).hasMessageContaining("differentMethod()"); 64 } 65 } 66 67 @Test 68 public void shouldVerifyInOrderWhenTwoChunksAreEqual() { 69 mockOne.simpleMethod(); 70 mockOne.simpleMethod(); 71 mockTwo.differentMethod(); 72 mockOne.simpleMethod(); 73 mockOne.simpleMethod(); 74 75 inOrder.verify(mockOne, times(2)).simpleMethod(); 76 inOrder.verify(mockTwo).differentMethod(); 77 inOrder.verify(mockOne, times(2)).simpleMethod(); 78 try { 79 inOrder.verify(mockOne, atLeastOnce()).simpleMethod(); 80 fail(); 81 } catch (VerificationInOrderFailure e) {} 82 } 83 84 @Test 85 public void shouldVerifyInOrderUsingMatcher() { 86 mockOne.simpleMethod(1); 87 mockOne.simpleMethod(2); 88 mockTwo.differentMethod(); 89 mockOne.simpleMethod(3); 90 mockOne.simpleMethod(4); 91 92 verify(mockOne, times(4)).simpleMethod(anyInt()); 93 94 inOrder.verify(mockOne, times(2)).simpleMethod(anyInt()); 95 inOrder.verify(mockTwo).differentMethod(); 96 inOrder.verify(mockOne, times(2)).simpleMethod(anyInt()); 97 try { 98 inOrder.verify(mockOne, times(3)).simpleMethod(anyInt()); 99 fail(); 100 } catch (VerificationInOrderFailure e) {} 101 } 102 } 103