用PowerMock mock final类
mock final类相对简单,直接贴代码
被测方法:
public class FinalEmployeeService { public void insertEmployee(Employee employee) { FinalEmployeeDao employeeDao = new FinalEmployeeDao(); employeeDao.insertEmployee(employee); } }
final 类
final public class FinalEmployeeDao { public boolean insertEmployee(Employee employee) { throw new UnsupportedOperationException(); } }
测试类:
@PrepareForTest(value={FinalEmployeeDao.class,FinalEmployeeService.class}) public class EmployeeServiceTestWithFinalClassTest extends PowerMockTestCase{ @ObjectFactory public ITestObjectFactory getObjectFactory() { return new PowerMockObjectFactory(); } @Test public void test() throws Exception { FinalEmployeeDao employeeDao = PowerMockito .mock(FinalEmployeeDao.class); Employee employee = new Employee(); PowerMockito.whenNew(FinalEmployeeDao.class).withNoArguments().thenReturn(employeeDao); PowerMockito.when(employeeDao.insertEmployee(employee)).thenReturn(true); FinalEmployeeService employeeService = new FinalEmployeeService(); employeeService.insertEmployee(employee); Mockito.verify(employeeDao).insertEmployee(employee); } }