@Test public void shouldNotQueueMessagesIfLooperIsQuit() throws Exception { HandlerThread ht = getHandlerThread(); Looper looper = ht.getLooper(); looper.quit(); assertThat(shadowOf(looper).hasQuit()).named("hasQuit").isTrue(); assertThat(shadowOf(looper).post(new Runnable() { @Override public void run() { } }, 0)).named("post").isFalse(); assertThat(shadowOf(looper).postAtFrontOfQueue(new Runnable() { @Override public void run() { } })).named("postAtFrontOfQueue").isFalse(); assertThat(shadowOf(looper).getScheduler().areAnyRunnable()).named("areAnyRunnable").isFalse(); }
@Test public void shouldThrowawayRunnableQueueIfLooperQuits() throws Exception { HandlerThread ht = getHandlerThread(); Looper looper = ht.getLooper(); shadowOf(looper).pause(); shadowOf(looper).post(new Runnable() { @Override public void run() { } }, 0); looper.quit(); assertThat(shadowOf(looper).hasQuit()).named("hasQuit").isTrue(); assertThat(shadowOf(looper).getScheduler().areAnyRunnable()).named("areAnyRunnable").isFalse(); assertThat(shadowOf(looper.getQueue()).getHead()).named("queue").isNull(); }
@Test public void soStaticRefsToLoopersInAppWorksAcrossTests_shouldRetainSameLooperForMainThreadBetweenResetsButGiveItAFreshScheduler() throws Exception { Looper mainLooper = Looper.getMainLooper(); Scheduler scheduler = shadowOf(mainLooper).getScheduler(); shadowOf(mainLooper).quit = true; assertThat(ApplicationProvider.getApplicationContext().getMainLooper()).isSameAs(mainLooper); Scheduler s = new Scheduler(); RuntimeEnvironment.setMasterScheduler(s); ShadowLooper.resetThreadLoopers(); Application application = new Application(); ReflectionHelpers.callInstanceMethod( application, "attach", ReflectionHelpers.ClassParameter.from( Context.class, ((Application) ApplicationProvider.getApplicationContext()).getBaseContext())); assertThat(Looper.getMainLooper()).named("Looper.getMainLooper()").isSameAs(mainLooper); assertThat(application.getMainLooper()).named("app.getMainLooper()").isSameAs(mainLooper); assertThat(shadowOf(mainLooper).getScheduler()).named("scheduler").isNotSameAs(scheduler); assertThat(shadowOf(mainLooper).getScheduler()).named("scheduler").isSameAs(s); assertThat(shadowOf(mainLooper).hasQuit()).named("quit").isFalse(); }