1.mock私有void方法
public class DemoService{
private void voidMethod(Long param1, Boolean param2){
System.out.println("mock private and void method");
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest(value = {DemoService.class})
DemoService demoService = PowerMockito.mock(DemoService.class);
PowerMockito.doNothing().when(demoService, "voidMethod", Mockito.any(Long.class), Mockito.any(Boolean.class)));
2.mock私有 有返回值的方法
public class DemoService{
private Boolean voidMethod(Long param1, Boolean param2){
System.out.println("mock private method");
if(param2){
return false;
}
return true;
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest(value = {DemoService.class})
DemoService demoService = PowerMockito.mock(DemoService.class);
PowerMockito.when(demoService, "voidMethod", Mockito.any(Long.class), Mockito.any(Boolean.class))).thenReturn(Boolean.FALSE);
3.测试私有void方法
public class DemoService{
private void voidMethod(Long param1, Boolean param2){
System.out.println("test private and void method");
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest(value = {DemoService.class})
DemoService demoService = PowerMockito.mock(DemoService.class);
PowerMockito.when(demoService, "voidMethod", Mockito.anyLong(), Mockito.anyBoolean()).thenCallRealMethod();
Whitebox.invokeMethod(demoService, "voidMethod", 1L, Boolean.TRUE);
4.测试私有 有返回值的方法
public class DemoService{
private Boolean voidMethod(Long param1, Boolean param2){
System.out.println("test private method");
if(param2){
return false;
}
return true;
}
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest(value = {DemoService.class})
DemoService demoService = PowerMockito.mock(DemoService.class);
PowerMockito.when(demoService, "voidMethod", Mockito.anyLong(), Mockito.anyBoolean()).thenCallRealMethod();
Boolean result= Whitebox.invokeMethod(demoService, "voidMethod", 1L, Boolean.TRUE);
Assert.assertFalse(result);
5.验证 私有 void是否执行
public class DemoService{
private void voidMethod(Long param1, Boolean param2){
System.out.println("test private and void method");
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest(value = {DemoService.class})
DemoService demoService = PowerMockito.mock(DemoService.class);
PowerMockito.when(demoService, "voidMethod", Mockito.anyLong(), Mockito.anyBoolean()).thenCallRealMethod();
Whitebox.invokeMethod(demoService, "voidMethod", 1L, Boolean.TRUE);
PowerMockito.verifyPrivate(demoService, times(0)).invoke("voidMethod", Mockito.any(Long.class), Mockito.any(Boolean.class));
6.mock静态方法
public class DemoService{
private static Boolean staticMethod(Long param1, Boolean param2){
return true;
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest(value = {DemoService.class})
@PowerMockIgnore({"javax.management.*"})
public class DemoServiceTest{
@Test
public void testStaticMethod() {
PowerMockito.mockStatic(DemoService.class);
when(DemoService.staticMethod(Mockito.any(Long.class), Mockito.any(Boolean.class))).thenReturn(true);
}
}