我为asyncTask编写了一个测试用例,如下所示。我发现无论我在CountDownlatch等待中使用什么超时,情况仍然可以通过。甚至比asyncTask中的睡眠时间还短。
有人可以启发我,为什么等待不超过超时抛出异常吗?
public class MyAsyncTask extends AsyncTask<Void, Void, Integer> {
@Override
protected Integer doInBackground(Void... voids) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 3;
}
}
@RunWith(RobolectricTestRunner.class)
public class MyAsyncTaskTest {
@Test
public void doInBackground_shouldCompleteInTime() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
MyAsyncTask task = new MyAsyncTask() {
@Override
protected void onPostExecute(Integer integer) {
assertThat(integer).isEqualTo(3);
latch.countDown();
}
};
task.execute();
latch.await(100, TimeUnit.MILLISECONDS); // not throw exception, why?
assertThat(latch.getCount()).isEqualTo(0);
}
}