在spring項目,假設我們有一個方法
//?一個executor,和普通定義線程池一樣(此處是spring自帶,@Scheduled注解用到的全局線程池)
@Resource
private?ThreadPoolTaskExecutor?executor;
//?另一個需要裝配的假定的服務
@Resource
private?AnotherService?anotherService;
//?CompletableFuture,需要被測試的方法
public?String?getProductBillSummaryList(String?input)?{
????//?異步操作
????CompletableFuture<String>?resultFuture?=?CompletableFuture.supplyAsync(
????????????()?->?anotherService.someMethod(input),?executor);
????
????//?等待執(zhí)行完畢
????CompletableFuture.allOf(resultFuture).join();
????try?{
????????String?s?=?resultFuture.get();
????????System.out.println(s);
????}?catch?(Exception?e)?{
????????e.printStackTrace();
????}
????return?null;
}
我們對這個方法單元測試,大概率就直接寫成:
@Mock
private?AnotherService?anotherService;
@InjectMocks
private?ProductTransactionSearchServiceImpl?productTransactionSearchService;
@Test
public?void?getProductBillSummaryList()?{
????Mockito.when(anotherService.someMethod(Mockito.any())).thenReturn("mockString");
????String?res?=?productTransactionSearchService.getProductBillSummaryList("input");
????Assert.assertNull(res);
}
這樣會導致Completable的線程不運行,一直阻塞在紅色箭頭指示的地方:
等待線程執(zhí)行完畢。然而線程并沒有執(zhí)行。
此時需要模擬并驅動異步線程的執(zhí)行,因此需要這樣寫:
@Mock
private?AnotherService?anotherService;
//?需要增加這個executor的mock
@Mock
private?ThreadPoolTaskExecutor?executor;
@InjectMocks
private?ProductTransactionSearchServiceImpl?productTransactionSearchService;
@Test
public?void?getProductBillSummaryList()?{
????Mockito.when(anotherService.someMethod(Mockito.any())).thenReturn("mockString");
????//?新增對異步線程里面Runnable方法的驅動
????Mockito.doAnswer(
????????(InvocationOnMock?invocation)?->?{
????????????((Runnable)?invocation.getArguments()[0]).run();
????????????return?null;
????????}
????).when(executor).execute(Mockito.any(Runnable.class));
????String?res?=?productTransactionSearchService.getProductBillSummaryList("input");
????Assert.assertNull(res);
}
這樣就mock了對Runnable方法的運行(就是執(zhí)行run方法,只要有調用就run,不阻塞)
運行單測就可以正常通過了。
參考
java - CompletableFuture usability and unit test - Stack Overflow文章來源:http://www.zghlxwxcb.cn/news/detail-697596.html
?文章來源地址http://www.zghlxwxcb.cn/news/detail-697596.html
到了這里,關于CompletableFuture的單元測試Mock的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!