假设我有两个类一起工作来执行这样的可调用对象:
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
类编写单元测试...使用模拟服务。突然之间,你围绕"它是异步的"的所有问题都消失了;因为"异步"部分在稀薄的空气中消失了。