Mockito:一个强大的用于 Java 开发的模拟测试框架实例
程序员文章站
2022-07-13 10:37:34
...
Mockito框架:
Mockito是一个基于MIT协议的开源java测试框架。
Mockito区别于其他模拟框架的地方主要是允许开发者在没有建立“预期”时验证被测系统的行为。对于mock对象的一个评价是测试系统的测试代码是一个高耦合的,由于 Mockito试图通过移除“期望规范”去除expect-run-verify(期望验证模式)的模式,因此在耦合度上有所降低。这样的结果是简化了测试代码,使他更易读和修改了。
使用Mockito框架的简单Java代码示例:
1.ClassPerson.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.单元测试类PersonServiceTest
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 ); } }