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

时间:2018-12-04 11:34:14

标签: java multithreading powermockito

我有一个代码段:

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的值是否为真。

1 个答案:

答案 0 :(得分:0)

找出该问题的答案

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);
相关问题