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