如何测试 ExecutorService 抛出的 RuntimeException

How to test an ExecutorService thrown RuntimeException

我正在尝试测试在 executorservice 运行 作业中抛出运行时异常的服务方法。然而,测试似乎并没有抓住它。我想是因为测试在执行程序作业完成之前完成。找个解决办法,同步测试什么的有什么技巧?

服务方式

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

测试

@Test
void migrateSplitFileRuntimeException() {
    assertThrows(RuntimeException.class,
            () -> {
                String runtimeWorkspace = "./test";

                File testDir = new File(runtimeWorkspace + "/inputfiles");
                FileUtils.forceMkdir(testDir);
                File fakeInputFile = new File(runtimeWorkspace + "/inputfiles/test.txt");
                FileUtils.writeStringToFile(fakeInputFile, "test", "UTF-8", true);

                String inputFile = ".\test\inputfiles\test.txt";

                File jobFile = new File(runtimeWorkspace + "/jobs.txt");
                File errorfile = new File(runtimeWorkspace + "/errors.txt");

                Mockito.doThrow(new Auth0Exception("")).when(importJobManager).executeImport(inputFile, runtimeWorkspace);

                auth0EngineService.migrateSplitFile(runtimeWorkspace, jobFile, errorfile, inputFile);

                FileUtils.deleteDirectory(new File(runtimeWorkspace));
            });
}

我愿意接受任何建议,在我实施我的测试运行的 executorservice 之前

您可以使用:

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

这将抛出任务执行期间发生的任何运行时异常。它也会阻塞,直到任务完成。