注意不是mock私有方法
假如对下面的代码进行测试:
public class Service {
private int getBackupSize(String backupId, String keycloakToken) {
//some code......
try {
backup = os.blockStorage().backups().get(backupId);
return backup.getSize();
} catch (Exception e) {
throw new EbsInternalServerException(EbsExceptionConstant.ERROR_CODE,
EbsExceptionConstant.ERROR_MESSAGE);
}
}
}
此时 @Rule
来判断异常的方式就行不通了,回归传统的 try...catch
方案。测试代码使用反射获取private方法,代码如下:
@Test
public void testWithException() {
//mock other codes...
try {
//String.class表示参数的类型,有几个参数就写几个
Method method = PowerMockito.method(Service.class, "getBackupSize", String.class, String.class);
method.invoke(service, "123", "123");
} catch (Exception e) {
//对异常进行断言
Assert.assertEquals(EbsExceptionConstant.ERROR_MESSAGE, e.getCause().getMessage());
}
}