有些对象需要mock的对象是由工厂方法产生出来的,而工厂方法一般是静态方法,这时候就需要同时mock工厂方法及对象
被测方法:
public class EmployeeServiceFactory { public void saveEmployee(Employee employee){ EmployeeDaoFactory dao = EmployeeDaoFactory.newInstance(); method("powermock"); dao.addEmployee(employee); } public void method(String str){ throw new UnsupportedOperationException(); } }
public class EmployeeDaoFactory { private EmployeeDaoFactory(){ } public static EmployeeDaoFactory newInstance(){ return new EmployeeDaoFactory(); } public void addEmployee(Employee employee) { throw new UnsupportedOperationException(); } }
测试类:
@PrepareForTest(value={EmployeeDaoFactory.class}) public class EmployeeServiceTestFactoryTest extends PowerMockTestCase{ @ObjectFactory public ITestObjectFactory getObjectFactory() { return new PowerMockObjectFactory(); } @Test public void addEmployee(){ EmployeeDaoFactory employeeDao = PowerMockito.mock(EmployeeDaoFactory.class); try { PowerMockito.mockStatic(EmployeeDaoFactory.class); PowerMockito.when(EmployeeDaoFactory.newInstance()).thenReturn(employeeDao); EmployeeServiceFactory service = PowerMockito.spy(new EmployeeServiceFactory()); PowerMockito.doNothing().when(service).method(Mockito.anyString()); Employee employee = new Employee(); service.saveEmployee(employee); Mockito.verify(service).method("powermock"); Mockito.verify(employeeDao).addEmployee(employee); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }