首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Mockito:一个强大的用以 Java 开发的模拟测试框架实例

2013-12-13 
Mockito:一个强大的用于 Java 开发的模拟测试框架实例public class Person{private final Integer personI

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 ); }}