案例
今天做单元测试调试接口,发现接口调用成功但是并没有运行线程池执行的方法,而是直接跳过执行代码
ExecutorService pool = Executors.newFixedThreadPool( 2 );
public void callInterfaceCreditease(final String idcard,final String name,final String mobile){
try{
ExecutorService pool = Executors.newFixedThreadPool( 2 );
//接口
pool.execute(new Runnable() {
@Override
public void run() {
creditCardCrediteaseService.doFetchCreditData(name, idcard, mobile);
}
});
//释放线程池资源
pool.shutdown();
}catch(Exception e){
log.error("调用接口异常:",e);
}
}
解决方案
原因是因为做单元测试时跟WEB项目不同,线程还没有开始启动,主线程已经关闭,只要我们加入一段代码,让主线程不关闭,这样就可以跑子线程的方法了
System.in.read();
@Test
public void testPostauthinfo() throws Exception {
TestRequest req = new TestRequest();
req.setPhoneNum( "13186666376" );
req.setAccountId( "3534e5334333333d434" );
req.setRegDate( Calendar.getInstance().getTime() );
req.setAuthResult( 1 );
req.setAuthDate( Calendar.getInstance().getTime() );
req.setBizKindName( "XNXYK" );
req.setRegSrcName( "IOS" );
req.setUserName( "张军" );
req.setIdCardNum( "xxxxxxxxxxxx" );
Bse64JsonResponse resp = encryptionBase64Param( Json.toJson( req ) );
restService.postauthinfo( resp.getSign(),
resp.getJsonStr() );
System.in.read();//加入该代码,让主线程不挂掉
}