假设我有两个类一起工作来执行这样的可调用:
public class blah {
@Autowired
private ExecutorServiceUtil executorServiceUtil;
@Autowired
private RestTemplate restClient;
public SomeReturnType getDepositTransactions(HttpHeaders httpHeaders) {
ExecutorService executor = executorServiceUtil.createExecuter();
try {
DepositTransactionsAsyncResponse asyncResponse = getPersonalCollectionAsyncResponse( httpHeaders, executor);
// do some processing
// return appropriate return type
}finally {
executorServiceUtil.shutDownExecutor(executor);
}
}
Future<ResponseEntity<PersonalCollectionResponse>> getPersonalCollectionAsyncResponse( HttpHeaders httpHeaders, ExecutorService executor) {
PersonalCollectionRequest personalCollectionRequest = getpersonalCollectionRequest(); // getPersonalCollectionRequest populates the request appropriately
return executor.submit(() -> restClient.exchange(personalCollectionRequest, httpHeaders, PersonalCollectionResponse.class));
}
}
public class ExecutorServiceUtil {
private static Logger log = LoggerFactory.getLogger(ExecutorServiceUtil.class);
public ExecutorService createExecuter() {
return Executors.newCachedThreadPool();
}
public void shutDownExecutor(ExecutorService executor) {
try {
executor.shutdown();
executor.awaitTermination(5, TimeUnit.SECONDS);
}
catch (InterruptedException e) {
log.error("Tasks were interrupted");
}
finally {
if (!executor.isTerminated()) {
log.error("Cancel non-finished tasks");
}
executor.shutdownNow();
}
}
}
如何使用 Mockito 存根响应并立即返回?
我已经尝试了以下但我的 innovcation.args() 返回 [null]
PowerMockito.when(executor.submit(Matchers.<Callable<ResponseEntity<OrxPendingPostedTrxCollectionResponseV3>>> any())).thenAnswer(new Answer<FutureTask<ResponseEntity<OrxPendingPostedTrxCollectionResponseV3>>>() {
@Override
public FutureTask<ResponseEntity<OrxPendingPostedTrxCollectionResponseV3>> answer(InvocationOnMock invocation) throws Throwable {
Object [] args = invocation.getArguments();
Callable<ResponseEntity<OrxPendingPostedTrxCollectionResponseV3>> callable = (Callable<ResponseEntity<OrxPendingPostedTrxCollectionResponseV3>>) args[0];
callable.call();
return null;
}
});
您可以通过不在ExecutorServiceUtil
测试代码中使用您来做到这一点。我的意思是:您为您的生产代码提供了该 util 类的模拟!
该模拟确实返回了“相同线程执行程序服务”;而不是“真正的服务”(基于线程池)。编写这样的同线程执行器实际上很简单 - 请参阅此处。
换句话说:您需要两个不同的单元测试:
ExecutorServiceUtil
类单独编写单元测试;确保它做它应该做的事情(我认为:检查它返回一个非空的 ExecutorService 几乎就足够了!)blah
班级编写单元测试......使用模拟服务。突然之间,所有围绕“异步”的问题都消失了;因为“异步”部分凭空消失了。本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句