Mockito:一个强大的用于 Java 开发的模拟测试框架实例
public class Person{ private final Integer personID; private final String personName; public Person( Integer personID, String personName ) { this.personID = personID; this.personName = personName; } public Integer getPersonID() { return personID; } public String getPersonName() { return personName; }}
?2.接口类PersonDAO.java
public interface PersonDao { public Person fetchPerson( Integer personID ); public void update( Person person );}
?3.类PersonService.java
public class PersonService{ private final PersonDao personDao; public PersonService( PersonDao personDao ) { this.personDao = personDao; } public boolean update( Integer personId, String name ) { Person person = personDao.fetchPerson( personId ); if( person != null ) { Person updatedPerson = new Person( person.getPersonID(), name ); personDao.update( updatedPerson ); return true; } else { return false; } }}
?4.单元测试类public class PersonServiceTest{ @Mock private PersonDao personDAO; private PersonService personService; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks( this ); personService = new PersonService( personDAO ); } @Test public void shouldUpdatePersonName() { Person person = new Person( 1, "Phillip" ); when( personDAO.fetchPerson( 1 ) ).thenReturn( person ); boolean updated = personService.update( 1, "David" ); assertTrue( updated ); verify( personDAO ).fetchPerson( 1 ); ArgumentCaptor<Person> personCaptor = ArgumentCaptor.forClass( Person.class ); verify( personDAO ).update( personCaptor.capture() ); Person updatedPerson = personCaptor.getValue(); assertEquals( "David", updatedPerson.getPersonName() ); // asserts that during the test, there are no other calls to the mock object. verifyNoMoreInteractions( personDAO ); } @Test public void shouldNotUpdateIfPersonNotFound() { when( personDAO.fetchPerson( 1 ) ).thenReturn( null ); boolean updated = personService.update( 1, "David" ); assertFalse( updated ); verify( personDAO ).fetchPerson( 1 ); verifyZeroInteractions( personDAO ); verifyNoMoreInteractions( personDAO ); }}