1 package org.robolectric; 2 3 import static com.google.common.truth.Truth.assertThat; 4 import static java.util.concurrent.TimeUnit.MILLISECONDS; 5 6 import java.util.concurrent.CountDownLatch; 7 import java.util.concurrent.atomic.AtomicBoolean; 8 import org.junit.Test; 9 import org.junit.runner.RunWith; 10 import org.junit.runners.JUnit4; 11 import org.robolectric.util.Scheduler; 12 13 @RunWith(JUnit4.class) 14 public class RuntimeEnvironmentTest { 15 16 @Test 17 public void setMainThread_forCurrentThread() { 18 RuntimeEnvironment.setMainThread(Thread.currentThread()); 19 assertThat(RuntimeEnvironment.getMainThread()).isSameAs(Thread.currentThread()); 20 } 21 22 @Test 23 public void setMainThread_forNewThread() { 24 Thread t = new Thread(); 25 RuntimeEnvironment.setMainThread(t); 26 assertThat(RuntimeEnvironment.getMainThread()).isSameAs(t); 27 } 28 29 @Test 30 public void isMainThread_forNewThread_withoutSwitch() throws InterruptedException { 31 final AtomicBoolean res = new AtomicBoolean(); 32 final CountDownLatch finished = new CountDownLatch(1); 33 Thread t = new Thread() { 34 @Override 35 public void run() { 36 res.set(RuntimeEnvironment.isMainThread()); 37 finished.countDown(); 38 } 39 }; 40 RuntimeEnvironment.setMainThread(Thread.currentThread()); 41 t.start(); 42 if (!finished.await(1000, MILLISECONDS)) { 43 throw new InterruptedException("Thread " + t + " didn't finish timely"); 44 } 45 assertThat(RuntimeEnvironment.isMainThread()).named("testThread").isTrue(); 46 assertThat(res.get()).named("thread t").isFalse(); 47 } 48 49 @Test 50 public void isMainThread_forNewThread_withSwitch() throws InterruptedException { 51 final AtomicBoolean res = new AtomicBoolean(); 52 final CountDownLatch finished = new CountDownLatch(1); 53 Thread t = new Thread() { 54 @Override 55 public void run() { 56 res.set(RuntimeEnvironment.isMainThread()); 57 finished.countDown(); 58 } 59 }; 60 RuntimeEnvironment.setMainThread(t); 61 t.start(); 62 if (!finished.await(1000, MILLISECONDS)) { 63 throw new InterruptedException("Thread " + t + " didn't finish timely"); 64 } 65 assertThat(RuntimeEnvironment.isMainThread()).named("testThread").isFalse(); 66 assertThat(res.get()).named("thread t").isTrue(); 67 } 68 69 @Test 70 public void isMainThread_withArg_forNewThread_withSwitch() throws InterruptedException { 71 Thread t = new Thread(); 72 RuntimeEnvironment.setMainThread(t); 73 assertThat(RuntimeEnvironment.isMainThread(t)).isTrue(); 74 } 75 76 @Test 77 public void getSetMasterScheduler() { 78 Scheduler s = new Scheduler(); 79 RuntimeEnvironment.setMasterScheduler(s); 80 assertThat(RuntimeEnvironment.getMasterScheduler()).isSameAs(s); 81 } 82 }