在实际的工做中,常常碰到只须要mock一个类的一部分方法,这时候能够用spy来实现。测试
被测类:spa
public class EmployeeService { public boolean exist(String userName) { checkPrivateExist(userName); checkPublicExist(userName); return true; } private void checkPrivateExist(String userName) { throw new UnsupportedOperationException(); } public void checkPublicExist(String userName){ throw new UnsupportedOperationException(); } }
若是要测试exist方法,须要mock checkPublicExist和checkPrivateExist方法,而不但愿mock exist方法code
测试类:blog
@PrepareForTest(EmployeeService.class) public class EmployeeServiceTestWithPrivateTest extends PowerMockTestCase{ @ObjectFactory public ITestObjectFactory getObjectFactory() { return new PowerMockObjectFactory(); } @Test public void testExist() { try { EmployeeService service = PowerMockito.spy(new EmployeeService()); PowerMockito.doNothing().when(service,"checkPrivateExist","powermock"); PowerMockito.doNothing().when(service).checkPublicExist("powermock");; boolean result = service.exist("powermock"); Assert.assertTrue(result); Mockito.verify(service).checkPublicExist("powermock"); PowerMockito.verifyPrivate(service).invoke("checkPrivateExist","powermock"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
在测试类中,真实的调用了exist方法。get
须要注意的是对private方法的mockit
PowerMockito.doNothing().when(service,"checkPrivateExist","powermock");io
以及对exist方法调用过程的验证class
Mockito.verify(service).checkPublicExist("powermock");
PowerMockito.verifyPrivate(service).invoke("checkPrivateExist","powermock");test