【问题标题】:How to stub asynchronous calls with mockito?如何使用 mockito 存根异步调用?
【发布时间】:2017-04-12 23:30:08
【问题描述】:

假设我有两个类一起工作以执行这样的可调用对象:

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

【问题讨论】:

  • 根据@GhostCat 的建议,我能够使调用同步返回,并允许我删除Answer 逻辑。

标签: java asynchronous mockito executorservice powermockito


【解决方案1】:

您可以通过在您的测试代码中使用您的ExecutorServiceUtil 来做到这一点。我的意思是:您为您的生产代码提供该 util 类的 mock

并且该模拟确实返回了“相同的线程执行器服务”;而不是“真正的服务”(基于线程池)。编写这样的同线程执行器实际上很简单 - 请参阅 here

换句话说:你想要两个在这里不同的单元测试:

  1. 您为ExecutorServiceUtil 类单独编写单元测试;确保它做它应该做的事情(我认为:检查它是否返回一个非空的 ExecutorService 几乎就足够了!)
  2. 您为blah 类编写单元测试...使用模拟服务。突然之间,你所有关于“它是异步的”的问题都消失了;因为“异步”部分消失得无影无踪。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    • 1970-01-01
    • 2017-04-17
    • 1970-01-01
    • 2012-01-20
    • 1970-01-01
    相关资源
    最近更新 更多