[英]Unit test for Runnable
我有以下代碼:
public class TypesEngine
{
@VisibleForTesting
void types(@NonNull final FindTypes findTypes, @NonNull final List<String> types)
{
final ExecutorService executorService = Executors.newFixedThreadPool(TYPES_NUMBER_OF_THREADS);
for (final String type : types)
{
executorService.execute(new Runnable()
{
@Override
public void run()
{
try
{
findTypes.getRelatedInformation(type);
}
catch (final TypeNotFound e)
{
log.info(String
.format(
"Caught TypeNotFound for type [%s].",
type));
}
}
});
}
executorService.shutdown();
}
}
我嘗試了以下單元測試:
@Test
public void test_Types() throws Exception
{
final List<String> types = Lists.newArrayList("type1","type2","type3");
doAnswer(new Answer() {
@Override
public Object answer(final InvocationOnMock invocation) throws Throwable {
throw new TypeNotFound();
}
}).when(findTypes).getRelatedInformation(anyString());
typesEngine.types(findTypes, types);
for(final String type : types)
{
verify(findTypes, times(1)).getRelatedInformation(type);
}
}
但它總是給我一個錯誤,即沒有調用驗證方法。 但是,如果我添加一個system.out.println,我可以看到正在調用不同的類型。
如果有人能告訴我如何寫下面的單元測試會很棒。
我正在使用Mockito進行單元測試。
您正在驗證在將任務提交給執行程序后立即調用了findTypes
。 執行者還沒有時間執行其任務。
由於在任務完成之前您無法阻止該設計,因此您需要在驗證之前保持足夠長的睡眠時間。 更可靠的方法是將執行程序服務作為參數傳遞,並調用awaitTermination()
來阻塞,直到執行程序完成,而不是休眠。
此外,您可以使用doThrow()
而不是doAnswer()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.