如何模拟包含匿名 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.
之后确定更新的值是否为真
找到这个问题的答案
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);
我有一个代码片段:
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.
之后确定更新的值是否为真找到这个问题的答案
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);