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