Search code examples
javamultithreadingpowermockito

How to mock executor service which contains the anonymous void method


I have a code snippet:

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  
   }
}

Now using Mockito i need to figure out whether the value of updated is true or not after executing the ex.submit.


Solution

  • Figured out the answer for this question

    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);