• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 package com.xtremelabs.robolectric.shadows;
2 
3 import static com.xtremelabs.robolectric.Robolectric.shadowOf;
4 import static org.junit.Assert.*;
5 
6 import com.xtremelabs.robolectric.Robolectric;
7 import com.xtremelabs.robolectric.WithTestDefaultsRunner;
8 
9 import org.junit.After;
10 import org.junit.Test;
11 import org.junit.runner.RunWith;
12 
13 import android.os.HandlerThread;
14 import android.os.Looper;
15 
16 @RunWith(WithTestDefaultsRunner.class)
17 public class HandlerThreadTest {
18 
19 	private HandlerThread handlerThread;
20 
21 	@After
tearDown()22 	public void tearDown() throws Exception {
23 		// Try to ensure we've exited the thread at the end of each test
24 		if ( handlerThread != null ) {
25 			handlerThread.quit();
26 			handlerThread.join();
27 		}
28 	}
29 
30     @Test
shouldReturnLooper()31     public void shouldReturnLooper() throws Exception {
32         handlerThread = new HandlerThread("test");
33         handlerThread.start();
34         assertNotNull(handlerThread.getLooper());
35         assertNotSame(handlerThread.getLooper(), Robolectric.application.getMainLooper());
36     }
37 
38     @Test
shouldReturnNullIfThreadHasNotBeenStarted()39     public void shouldReturnNullIfThreadHasNotBeenStarted() throws Exception {
40         handlerThread = new HandlerThread("test");
41         assertNull(handlerThread.getLooper());
42     }
43 
44     @Test
shouldQuitLooperAndThread()45     public void shouldQuitLooperAndThread() throws Exception {
46         handlerThread = new HandlerThread("test");
47         handlerThread.start();
48         assertTrue(handlerThread.isAlive());
49         assertTrue(handlerThread.quit());
50         handlerThread.join();
51         assertFalse(handlerThread.isAlive());
52         handlerThread = null;
53     }
54 
55     @Test
shouldStopThreadIfLooperIsQuit()56     public void shouldStopThreadIfLooperIsQuit() throws Exception {
57         handlerThread = new HandlerThread("test1");
58         handlerThread.start();
59         Looper looper = handlerThread.getLooper();
60         assertFalse(shadowOf(looper).quit);
61         looper.quit();
62         handlerThread.join();
63         assertFalse(handlerThread.isAlive());
64         assertTrue(shadowOf(looper).quit);
65         handlerThread = null;
66     }
67 
68     @Test
shouldCallOnLooperPrepared()69     public void shouldCallOnLooperPrepared() throws Exception {
70         final Boolean[] wasCalled = new Boolean[] { false };
71         handlerThread = new HandlerThread("test") {
72             @Override
73             protected void onLooperPrepared() {
74                 wasCalled[0] = true;
75             }
76         };
77         handlerThread.start();
78         assertNotNull(handlerThread.getLooper());
79         assertTrue(wasCalled[0]);
80     }
81 }
82