mock中测试private方法,不是mock:
Method method = PowerMockito.method(CategoryController.class, "getCategory",List.class);//创建调用CategoryController类中的getCategory私有方法的method对象,参数是list对象
List<Category> category_all_actual = (List<Category>)method.invoke(categoryController, categories);//调用categoryController的私有方法,返回list对象,参数是list对象
assertArrayEquals(category_all_expect.toArray(), category_all_actual.toArray());//比较实际返回的对象与期望的对象是否相等.
或者:// PowerMockito.doReturn(index_expect).when(controller, "processPage", pageCode, request, response, model); // Mock私有方法
或者:// PowerMockito.when(controller, "processPage", pageCode, request, response, model).thenReturn(index_expect); // Mock私有方法
用PowerMock spy mock private方法:
官方文档: https://github.com/powermock/powermock/wiki/Mockito#how-to-verify-private-behavior
在实际的工作中,经常碰到只需要mock一个类的一部分方法,这时候可以用spy来实现。
被测类:
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方法
测试类:
@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方法。
需要注意的是对private方法的mock
PowerMockito.doNothing().when(service,"checkPrivateExist","powermock");
以及对exist方法调用过程的验证
Mockito.verify(service).checkPublicExist("powermock");
PowerMockito.verifyPrivate(service).invoke("checkPrivateExist","powermock");