ModernAsyncTaskTest.java revision fad2335f169d36b7b6f2c0ec8ddfe6c0094c2072
1/* 2 * Copyright (C) 2016 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License 15 */ 16 17package android.support.v4.content; 18 19import static org.junit.Assert.fail; 20 21import android.support.test.InstrumentationRegistry; 22import android.support.test.runner.AndroidJUnit4; 23import android.test.suitebuilder.annotation.LargeTest; 24 25import org.junit.Test; 26import org.junit.runner.RunWith; 27 28import java.util.concurrent.CountDownLatch; 29import java.util.concurrent.TimeUnit; 30 31@RunWith(AndroidJUnit4.class) 32public class ModernAsyncTaskTest { 33 34 ModernAsyncTask mModernAsyncTask; 35 36 /** 37 * Test to ensure that onCancelled is always called, even if doInBackground throws an exception. 38 * 39 * @throws Throwable 40 */ 41 @LargeTest 42 @Test 43 public void testCancellationWithException() throws Throwable { 44 final CountDownLatch readyToCancel = new CountDownLatch(1); 45 final CountDownLatch readyToThrow = new CountDownLatch(1); 46 final CountDownLatch calledOnCancelled = new CountDownLatch(1); 47 InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() { 48 @Override 49 public void run() { 50 mModernAsyncTask = new ModernAsyncTask() { 51 @Override 52 protected Object doInBackground(Object[] params) { 53 readyToCancel.countDown(); 54 try { 55 readyToThrow.await(); 56 } catch (InterruptedException e) {} 57 // This exception is expected to be caught and ignored 58 throw new RuntimeException(); 59 } 60 61 @Override 62 protected void onCancelled(Object o) { 63 calledOnCancelled.countDown(); 64 } 65 }; 66 } 67 }); 68 69 mModernAsyncTask.execute(); 70 if (!readyToCancel.await(5, TimeUnit.SECONDS)) { 71 fail("Test failure: doInBackground did not run in time."); 72 } 73 mModernAsyncTask.cancel(false); 74 readyToThrow.countDown(); 75 if (!calledOnCancelled.await(5, TimeUnit.SECONDS)) { 76 fail("onCancelled not called!"); 77 } 78 } 79} 80