1 package com.xtremelabs.robolectric.shadows; 2 3 import android.view.ViewTreeObserver; 4 import com.xtremelabs.robolectric.Robolectric; 5 import com.xtremelabs.robolectric.WithTestDefaultsRunner; 6 import org.junit.Before; 7 import org.junit.Test; 8 import org.junit.runner.RunWith; 9 10 import java.util.List; 11 12 import static com.xtremelabs.robolectric.Robolectric.shadowOf; 13 import static org.junit.Assert.assertFalse; 14 import static org.junit.Assert.assertTrue; 15 16 @RunWith(WithTestDefaultsRunner.class) 17 public class ViewTreeObserverTest { 18 19 private ViewTreeObserver viewTreeObserver; 20 private TestOnGlobalLayoutListener listener1; 21 private TestOnGlobalLayoutListener listener2; 22 23 @Before setUp()24 public void setUp() throws Exception { 25 viewTreeObserver = Robolectric.Reflection.newInstanceOf(ViewTreeObserver.class); 26 listener1 = new TestOnGlobalLayoutListener(); 27 listener2 = new TestOnGlobalLayoutListener(); 28 } 29 30 @Test shouldRecordMultipleOnGlobalLayoutListenersAndFireThemWhenAsked()31 public void shouldRecordMultipleOnGlobalLayoutListenersAndFireThemWhenAsked() throws Exception { 32 viewTreeObserver.addOnGlobalLayoutListener(listener1); 33 viewTreeObserver.addOnGlobalLayoutListener(listener2); 34 35 shadowOf(viewTreeObserver).fireOnGlobalLayoutListeners(); 36 assertTrue(listener1.onGlobalLayoutWasCalled); 37 assertTrue(listener2.onGlobalLayoutWasCalled); 38 39 listener1.reset(); 40 listener2.reset(); 41 viewTreeObserver.removeGlobalOnLayoutListener(listener1); 42 shadowOf(viewTreeObserver).fireOnGlobalLayoutListeners(); 43 44 assertFalse(listener1.onGlobalLayoutWasCalled); 45 assertTrue(listener2.onGlobalLayoutWasCalled); 46 47 listener1.reset(); 48 listener2.reset(); 49 viewTreeObserver.removeGlobalOnLayoutListener(listener2); 50 shadowOf(viewTreeObserver).fireOnGlobalLayoutListeners(); 51 52 assertFalse(listener1.onGlobalLayoutWasCalled); 53 assertFalse(listener2.onGlobalLayoutWasCalled); 54 } 55 56 @Test getGlobalLayoutListeners_shouldReturnTheListeners()57 public void getGlobalLayoutListeners_shouldReturnTheListeners() throws Exception { 58 viewTreeObserver.addOnGlobalLayoutListener(listener1); 59 viewTreeObserver.addOnGlobalLayoutListener(listener2); 60 61 List<ViewTreeObserver.OnGlobalLayoutListener> listeners = shadowOf(viewTreeObserver).getOnGlobalLayoutListeners(); 62 assertTrue(listeners.size() == 2); 63 assertTrue(listeners.contains(listener1)); 64 assertTrue(listeners.contains(listener2)); 65 } 66 67 private static class TestOnGlobalLayoutListener implements ViewTreeObserver.OnGlobalLayoutListener { 68 boolean onGlobalLayoutWasCalled; 69 70 @Override onGlobalLayout()71 public void onGlobalLayout() { 72 onGlobalLayoutWasCalled = true; 73 } 74 reset()75 public void reset() { 76 onGlobalLayoutWasCalled = false; 77 } 78 } 79 } 80