0

我正在尝试测试在 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 之前,我愿意接受任何建议,我的测试正在运行

4

1 回答 1

1

您可以使用:

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

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

于 2020-02-11T14:45:41.007 回答