org.powermock
powermock-api-mockito-common
1.6.5
org.powermock
powermock-module-junit4
1.6.3
test
org.powermock
powermock-api-mockito
1.6.5
test
OrderRechargeService mock = PowerMockito.mock(OrderRechargeService.class);
@Mock
private OrderRechargeService rechargeService;
@InjectMocks
private OrderRechargeHandlerResultGatewayServiceImpl service;
当使用注解时,需要有个注解的类的一个初始化过程,有两种方式:
PowerMockito.when(orderRechargeService.updateByRequestNo(Matchers.any())).thenReturn(true);
/**
* mock 无返回值的方法
*/
PowerMockito.doNothing().when(mockService).methodWithVoid();
/**
* 当使用mock对象去调用某个方法时,要使用thenCallRealMethod();
*/
PowerMockito.when(mock,"methodName").thenCallRealMethod();
Mock 构造方法
File file = PowerMockito.mock(File.class);
PowerMockito.whenNew(File.class).withArguments("bing").thenReturn(file);
ClassWithFinalMethod mock= PowerMockito.mock(ClassWithFinalMethod.class);
PowerMockito.when(mock.finalMethod()).thenReturn(someThing);
PowerMockito.when(service,"privateMethod").thenReturn(someThing);
PowerMockito.mockStatic(ClassWithStaticMethod.class);
PowerMockito.when(ClassWithStaticMethod.staticMethod()).thenReturn(someThing);
Whitebox.setInternalState(service, "anyfield", value);
Whitebox.getInternalState(service,"field");
PowerMockito.when(service.method()).then(new Answer(){
public methodReturnObject answer(InvocationOnMock invocation){
invocation.callRealMethod():调用真正的方法
invocation.getArguments():获取所有参数
invocation.getMethod():返回mock实例调用的方法
invocation.getMock():获取mock实例
if ... return null;
}
});
Mockito.verify(mockService).mockedMethod(parameters);
Mockito.verify(mockService,never()).mockedMethod(parameters);
Mockito.verify(mockService,times(1)).mockedMethod(parameters);
PowerMockito.verifyNew();
PowerMockito.verifyPrivate();
PowerMockito.verifyStatic();