ModernAsyncTaskTest.java revision db7cc953f35069e445cf1dd1d59058b9b1665e5c
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 android.support.test.InstrumentationRegistry;
20import android.support.test.runner.AndroidJUnit4;
21
22import org.junit.Test;
23import org.junit.runner.RunWith;
24
25import java.util.concurrent.CountDownLatch;
26import java.util.concurrent.TimeUnit;
27
28import static org.junit.Assert.*;
29
30@RunWith(AndroidJUnit4.class)
31public class ModernAsyncTaskTest {
32
33    ModernAsyncTask mModernAsyncTask;
34
35    /**
36     * Test to ensure that onCancelled is always called, even if doInBackground throws an exception.
37     *
38     * @throws Throwable
39     */
40    @Test
41    public void testCancellationWithException() throws Throwable {
42        final CountDownLatch readyToCancel = new CountDownLatch(1);
43        final CountDownLatch readyToThrow = new CountDownLatch(1);
44        final CountDownLatch calledOnCancelled = new CountDownLatch(1);
45        InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
46            @Override
47            public void run() {
48                mModernAsyncTask = new ModernAsyncTask() {
49                    @Override
50                    protected Object doInBackground(Object[] params) {
51                        readyToCancel.countDown();
52                        try {
53                            readyToThrow.await();
54                        } catch (InterruptedException e) {}
55                        // This exception is expected to be caught and ignored
56                        throw new RuntimeException();
57                    }
58
59                    @Override
60                    protected void onCancelled(Object o) {
61                        calledOnCancelled.countDown();
62                    }
63                };
64            }
65        });
66
67        mModernAsyncTask.execute();
68        if (!readyToCancel.await(5, TimeUnit.SECONDS)) {
69            fail("Test failure: doInBackground did not run in time.");
70        }
71        mModernAsyncTask.cancel(false);
72        readyToThrow.countDown();
73        if (!calledOnCancelled.await(5, TimeUnit.SECONDS)) {
74            fail("onCancelled not called!");
75        }
76    }
77}
78