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 package com.android.settingslib.utils;
17 
18 
19 import static com.google.common.truth.Truth.assertThat;
20 import static org.junit.Assert.fail;
21 
22 import org.junit.Test;
23 import org.junit.runner.RunWith;
24 import org.robolectric.RobolectricTestRunner;
25 import org.robolectric.shadows.ShadowLooper;
26 
27 @RunWith(RobolectricTestRunner.class)
28 public class ThreadUtilsTest {
29 
30     @Test
testMainThread()31     public void testMainThread() throws InterruptedException {
32         assertThat(ThreadUtils.isMainThread()).isTrue();
33         Thread background = new Thread(new Runnable() {
34             public void run() {
35                 assertThat(ThreadUtils.isMainThread()).isFalse();
36             }
37         });
38         background.start();
39         background.join();
40     }
41 
42     @Test
testEnsureMainThread()43     public void testEnsureMainThread() throws InterruptedException {
44         ThreadUtils.ensureMainThread();
45         Thread background = new Thread(new Runnable() {
46             public void run() {
47                 try {
48                     ThreadUtils.ensureMainThread();
49                     fail("Should not pass ensureMainThread in a background thread");
50                 } catch (RuntimeException e) {
51                 }
52             }
53         });
54         background.start();
55         background.join();
56     }
57 
58     @Test
testPostOnMainThread_shouldRunOnMainTread()59     public void testPostOnMainThread_shouldRunOnMainTread() throws Exception {
60         TestRunnable cr = new TestRunnable();
61         ShadowLooper.pauseMainLooper();
62         ThreadUtils.postOnMainThread(cr);
63         assertThat(cr.called).isFalse();
64 
65         ShadowLooper.runUiThreadTasks();
66         assertThat(cr.called).isTrue();
67         assertThat(cr.onUiThread).isTrue();
68     }
69 
70     private static class TestRunnable implements Runnable {
71         volatile boolean called;
72         volatile boolean onUiThread;
73 
run()74         public void run() {
75             this.called = true;
76             this.onUiThread = ThreadUtils.isMainThread();
77         }
78     }
79 
80 }
81