Java 如何测试ExecutorService引发的RuntimeException

Java 如何测试ExecutorService引发的RuntimeException,java,juniper,Java,Juniper,我正在尝试测试一个服务方法,该方法在executorservice运行的作业中引发runtimeexception。然而,测试似乎没有抓住它。我想是因为测试在执行器工作完成之前就完成了。找到解决方案、同步测试或其他什么的诀窍是什么 服务方式 public void migrateSplitFile(String runtimeWorkspace, File jobFile, File errorFile, String inputFile) { ExecutorService execu

我正在尝试测试一个服务方法,该方法在executorservice运行的作业中引发runtimeexception。然而,测试似乎没有抓住它。我想是因为测试在执行器工作完成之前就完成了。找到解决方案、同步测试或其他什么的诀窍是什么

服务方式

public void migrateSplitFile(String runtimeWorkspace, File jobFile, File errorFile, String inputFile) {
    ExecutorService executorService = Executors.newFixedThreadPool(maxImportJobs);
    executorService.execute(()->{
        try {
            importSingleFile(runtimeWorkspace, jobFile, errorFile, inputFile);
        } catch (IOException e) {
            throw new RuntimeException("Failed running import for file [" + inputFile + "]", e);
        }
    });
}

private void importSingleFile(String runtimeWorkspace, File jobFile, File errorFile, String inputFile) throws IOException {
    Optional<RunningJob> jobResult = importJobManager.executeImport(inputFile, runtimeWorkspace);
    if (jobResult.isPresent()) {
        RunningJob job = jobResult.get();
        fileUtils.writeStringToFile(jobFile, "Ran job [" + job.getJobId() + "] for input file [" + inputFile + "]");
    } else {
        fileUtils.writeStringToFile(errorFile, "input file [" + inputFile + "] failed to process");
    }
}
我愿意接受任何建议,在我实施Executor服务之前,我的测试正在运行

您可以使用:

Future<?> f = executorService.submit(()->{
    try {
        importSingleFile(runtimeWorkspace, jobFile, errorFile, inputFile);
    } catch (IOException e) {
        throw new RuntimeException("Failed running import for file [" + inputFile + "]", e);
    }
});

这将引发任务执行期间发生的任何运行时异常。它还将一直阻止,直到任务完成。

什么是
importJobManager
?您可以在提交任务时获取未来,然后,当您调用get.importJobManager时,他们会抛出异常。importJobManager只是一个类,它执行一些业务逻辑,以实际执行导入。我目前正在尝试使用futures来捕获它,但还没有找到解决方案。我不太精通多线程,我不知道你的测试与上面的代码和executor服务有什么关系?使用future.get将导致测试等待任务完成,如果任务引发异常,则会引发异常。很抱歉,回复太晚,我已经为此工作了一整天。我在futures上尝试了get调用,但这使得整个过程都阻塞了,我希望两个导入作业同时运行,每个导入作业都以顺序方式运行,我没有注意到任何显著的速度提升,这使得它成为多线程的。仍在寻找解决方案atm@kenny在这种情况下,您可能需要在问题中提供更多信息。Future#get将阻止并让您查看已执行任务的结果。如果您试图并行运行测试,那么我认为您需要稍微从任务中退一步。将测试设计为独立运行,您的框架将有一个并行选项。我接受了两天的培训,周一我将返回工作岗位,看看是否找不到其他解决方案,可能会重构一些代码并独立测试,并承担几行代码无法测试的风险,不过,我不太喜欢这一点……我们最终决定不运行多线程的特定代码段,因此我的问题与手头的工作不再相关。然而,我确实相信,如果再投入一点时间,建议的答案会产生我想要的结果
Future<?> f = executorService.submit(()->{
    try {
        importSingleFile(runtimeWorkspace, jobFile, errorFile, inputFile);
    } catch (IOException e) {
        throw new RuntimeException("Failed running import for file [" + inputFile + "]", e);
    }
});
f.get();