繁体   English   中英

如何模拟包含匿名void方法的执行程序服务

[英]How to mock executor service which contains the anonymous void method

我有一个代码片段:

public void data(Customer customer) {  
   boolean updated = false;  
   ExectorService ex=Executors.newCachedThreadPool();  
   ex.submit(()->customertoDB(customer,updated));  
}  

void customertoDB(Customer customer,boolean updated) {  
   try{  
     //code to update the DB or third party service  
     updated=true;  
   }  
   catch(Exception e) {  
     //catching Exception  
   }
}

现在使用Mockito,我需要在执行ex.submit之后弄清update的值是否为true。

找出这个问题的答案

PowerMockito.mockStatic(Executors.class);  
ExectorService exMock = PowerMockito.mock(ExectorService.class);  
PowerMockito.when(exMock.submit(Mockito.any(Runnable.class))).thenAnswer(new Answer<Object>() {
   @Override  
   public Object answer(InvocationOnMock invocation) throws Runnable {  
      ClassName.customertoDB(customer,updated))  
      return null;  
   }  
 });
assertThat(updated).isEqualTo(true);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM