【发布时间】:2018-06-19 15:04:47
【问题描述】:
我在控制器中有一个简单的端点,因为它是:
private final ExecutorService threadPoolExecutor = Executors.newFixedThreadPool(6);
@PostMapping(path = "/batch")
public ServiceResponse batch(@RequestBody BatchRequest request) {
threadPoolExecutor.submit(() -> {
try {
service.batch(request);
log.info("Batch finished");
} catch (Exception e) {
log.error("Failed to execute. Cause: ");
e.printStackTrace();
}
});
return ServiceResponse.asSuccess("Ok");
}
这样做是因为服务可能需要几分钟才能运行,因此我们避免锁定整个系统。我正在尝试对此进行单元测试并捕获它的异常(增加代码覆盖率)。这是我到现在才想到的
@Rule
public ExpectedException exception = ExpectedException.none();
@InjectMocks
private MyController controller;
@MockBean
private MyService service;
@Test
public void testBatchThrowsException() throws Exception {
createRequest();
when(service.batch(any())).thenThrow(Exception.class);
mockMvc.perform(post(Controller.URL_PREFIX+"/batch")
.contentType(MediaType.APPLICATION_JSON)
.content(request.toString()))
.andDo(MockMvcResultHandlers.print())
.andExpect(status().isOk());
exception.expect(Exception.class);
}
当然它会返回成功,因为请求结束时线程仍在运行。有没有办法模拟执行者并获得结果或类似的东西?我尝试过使用 Awaitility,但无法正确调用 lambda 函数。
【问题讨论】:
标签: multithreading spring-boot junit mockito