VisibilityTracker { void addView(@NonNull final View view, final int minPercentageViewed) { TrackingInfo trackingInfo = mTrackedViews.get(view); if (trackingInfo == null) { trackingInfo = new TrackingInfo(); mTrackedViews.put(view, trackingInfo); scheduleVisibilityCheck(); } trackingInfo.mMinViewablePercent = minPercentageViewed; trackingInfo.mAccessOrder = mAccessCounter; mAccessCounter++; if (mAccessCounter % NUM_ACCESSES_BEFORE_TRIMMING == 0) { trimTrackedViews(mAccessCounter - NUM_ACCESSES_BEFORE_TRIMMING); } } VisibilityTracker(@NonNull final Context context); @VisibleForTesting  VisibilityTracker(@NonNull final Context context,
            @NonNull final Map<View, TrackingInfo> trackedViews,
            @NonNull final VisibilityChecker visibilityChecker,
            @NonNull final Handler visibilityHandler);   }
@Test public void addView_withVisibleView_shouldAddVisibleViewToTrackedViews() throws Exception { subject.addView(view, MIN_PERCENTAGE_VIEWED); assertThat(trackedViews).hasSize(1); }
@Test(expected = AssertionError.class) public void addView_whenViewIsNull_shouldThrowNPE() throws Exception { subject.addView(null, MIN_PERCENTAGE_VIEWED); assertThat(trackedViews).isEmpty(); }
@Test public void visibilityRunnable_run_withVisibleView_shouldCallOnVisibleCallback() throws Exception { subject.addView(view, MIN_PERCENTAGE_VIEWED); subject.new VisibilityRunnable().run(); verify(visibilityTrackerListener).onVisibilityChanged( Lists.newArrayList(view), Lists.<View>newArrayList()); }
@Test public void visibilityRunnable_run_withNonVisibleView_shouldCallOnNonVisibleCallback() throws Exception { when(view.getVisibility()).thenReturn(View.INVISIBLE); subject.addView(view, MIN_PERCENTAGE_VIEWED); subject.new VisibilityRunnable().run(); ArgumentCaptor<List> visibleCaptor = ArgumentCaptor.forClass(List.class); ArgumentCaptor<List> invisibleCaptor = ArgumentCaptor.forClass(List.class); verify(visibilityTrackerListener).onVisibilityChanged(visibleCaptor.capture(), invisibleCaptor.capture()); assertThat(visibleCaptor.getValue().size()).isEqualTo(0); assertThat(invisibleCaptor.getValue().size()).isEqualTo(1); }
@Test public void addView_shouldClearViewAfterNumAccesses() { subject.addView(view, MIN_PERCENTAGE_VIEWED); assertThat(trackedViews).hasSize(1); for (int i = 0; i < VisibilityTracker.NUM_ACCESSES_BEFORE_TRIMMING - 2; ++i) { subject.addView(view2, MIN_PERCENTAGE_VIEWED); } assertThat(trackedViews).hasSize(2); subject.addView(view2, MIN_PERCENTAGE_VIEWED); assertThat(trackedViews).hasSize(2); for (int i = 0; i < VisibilityTracker.NUM_ACCESSES_BEFORE_TRIMMING - 1; ++i) { subject.addView(view2, MIN_PERCENTAGE_VIEWED); } assertThat(trackedViews).hasSize(2); subject.addView(view2, MIN_PERCENTAGE_VIEWED); assertThat(trackedViews).hasSize(1); }