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.annotation; 7 8 import org.junit.Test; 9 import org.mockito.ArgumentCaptor; 10 import org.mockito.Captor; 11 import org.mockito.Mock; 12 import org.mockitousage.IMethods; 13 import org.mockitoutil.TestBase; 14 15 import java.util.LinkedList; 16 import java.util.List; 17 18 import static junit.framework.TestCase.assertEquals; 19 import static junit.framework.TestCase.assertSame; 20 import static org.mockito.Mockito.verify; 21 22 @SuppressWarnings("unchecked") 23 public class CaptorAnnotationBasicTest extends TestBase { 24 25 public class Person { 26 private final String name; 27 private final String surname; 28 29 public Person(String name, String surname) { 30 this.name = name; 31 this.surname = surname; 32 } 33 34 public String getName() { 35 return name; 36 } 37 38 public String getSurname() { 39 return surname; 40 } 41 } 42 43 public interface PeopleRepository { 44 void save(Person capture); 45 } 46 47 @Mock PeopleRepository peopleRepository; 48 49 private void createPerson(String name, String surname) { 50 peopleRepository.save(new Person(name, surname)); 51 } 52 53 @Test 54 public void shouldUseCaptorInOrdinaryWay() { 55 //when 56 createPerson("Wes", "Williams"); 57 58 //then 59 ArgumentCaptor<Person> captor = ArgumentCaptor.forClass(Person.class); 60 verify(peopleRepository).save(captor.capture()); 61 assertEquals("Wes", captor.getValue().getName()); 62 assertEquals("Williams", captor.getValue().getSurname()); 63 } 64 65 @Captor ArgumentCaptor<Person> captor; 66 67 @Test 68 public void shouldUseAnnotatedCaptor() { 69 //when 70 createPerson("Wes", "Williams"); 71 72 //then 73 verify(peopleRepository).save(captor.capture()); 74 assertEquals("Wes", captor.getValue().getName()); 75 assertEquals("Williams", captor.getValue().getSurname()); 76 } 77 78 @SuppressWarnings("rawtypes") 79 @Captor ArgumentCaptor genericLessCaptor; 80 81 @Test 82 public void shouldUseGenericlessAnnotatedCaptor() { 83 //when 84 createPerson("Wes", "Williams"); 85 86 //then 87 verify(peopleRepository).save((Person) genericLessCaptor.capture()); 88 assertEquals("Wes", ((Person) genericLessCaptor.getValue()).getName()); 89 assertEquals("Williams", ((Person) genericLessCaptor.getValue()).getSurname()); 90 } 91 92 @Captor ArgumentCaptor<List<String>> genericListCaptor; 93 @Mock IMethods mock; 94 95 @Test 96 public void shouldCaptureGenericList() { 97 //given 98 List<String> list = new LinkedList<String>(); 99 mock.listArgMethod(list); 100 101 //when 102 verify(mock).listArgMethod(genericListCaptor.capture()); 103 104 //then 105 assertSame(list, genericListCaptor.getValue()); 106 } 107 } 108