上面的例子是很理想化的状态,但是在实际的开发中,我们需要经常调用一些依赖特定环境的函数或者调用同事写的代码,而同事仅提供了接口。这个时候就需要利用Mockito来协助我们完成测试。
当然,你可以选择easyMock ,jmock等mock工具
在这里直接引用《PowerMock实战手册》中的例子
待测类:
public class EmployeeService { private EmployeeDao employeeDao; public EmployeeService(EmployeeDao employeeDao) { this.employeeDao = employeeDao; } }
待测类调用的方法
public class EmployeeDao { public int getTotal() { throw new UnsupportedOperationException(); } }
其中 getTotal 就是一个利用正常办法无法测试的函数。
测试类:
public class EmployeeServiceTest { @Mock private EmployeeDao employeeDao; EmployeeService employeeService; @BeforeMethod public void init(){ MockitoAnnotations.initMocks(this); employeeService = new EmployeeService(employeeDao); } @Test public void testGetTotalEmployee() { PowerMockito.when(employeeDao.getTotal()).thenReturn(10); int total = employeeService.getTotalEmployee(); assertEquals(10, total); } }
@Mock 是Mockito的标记 与MockitoAnnotations.initMocks(this) 配合使用,等效于
EmployeeDao employeeDao = Mockito.mock(EmployeeDao.class)
如果些对象在测试类反复使用的话,前一种写法能节省很多代码
@BeforeMethod 是testNG标记 ,作用是在运行很一个测试方法之前运行此方法
@Test testNG标识,表明此方法是一个测试方法
PowerMockito.when(employeeDao.getTotal()).thenReturn(10);
录制mock的行为,当调用getTotal方法时,返回10
具体请参照:http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html
下面是运行结果:
[TestNG] Running: C:UserschangzhzAppDataLocalTemp estng-eclipse--599967477 estng-customsuite.xml PASSED: testGetTotalEmployee =============================================== Default test Tests run: 1, Failures: 0, Skips: 0 =============================================== =============================================== Default suite Total tests run: 1, Failures: 0, Skips: 0 =============================================== [TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@5f205aa: 49 ms [TestNG] Time taken by org.testng.reporters.JUnitReportReporter@424c0bc4: 8 ms [TestNG] Time taken by org.testng.reporters.jq.Main@2ff5659e: 37 ms [TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 1 ms [TestNG] Time taken by org.testng.reporters.EmailableReporter2@1996cd68: 3 ms [TestNG] Time taken by org.testng.reporters.XMLReporter@27ddd392: 5 ms