UberButton extends AppCompatButton { @NonNull protected Activity getActivity() { Context context = getContext(); while (!(context instanceof Activity) && context instanceof ContextWrapper) { context = ((ContextWrapper) context).getBaseContext(); } if (context instanceof Activity) { return (Activity) context; } throw new IllegalStateException("Button is not attached to an activity."); } UberButton(Context context);  UberButton(Context context, AttributeSet attrs);  UberButton(Context context, AttributeSet attrs, int defStyleAttr);  UberButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes); @Override void setBackgroundResource(@DrawableRes int backgroundResource);  }
@Test public void getActivity_whenAttachedToActivity_shouldReturnActivity() { final Activity testActivity = Robolectric.setupActivity(Activity.class); final UberButton uberButton = new UberButton(testActivity, null, 0, 0) { }; assertThat(uberButton.getActivity()).isSameAs(testActivity); }
@Test public void getActivity_whenContextWrapper_shouldReturnActivity() { final Activity testActivity = Robolectric.setupActivity(Activity.class); final ContextThemeWrapper contextThemeWrapper = new ContextThemeWrapper(testActivity, 0); UberButton uberButton = new UberButton(contextThemeWrapper, null, 0, 0) { }; assertThat(uberButton.getActivity()).isSameAs(testActivity); }
@Test public void getActivity_whenContextWrapperNested_shouldReturnActivity() { final Activity testActivity = Robolectric.setupActivity(Activity.class); final ContextThemeWrapper nestedWrapper = new ContextThemeWrapper(testActivity, 0); final ContextThemeWrapper wrapper = new ContextThemeWrapper(nestedWrapper, 0); UberButton uberButton = new UberButton(wrapper, null, 0, 0) { }; assertThat(uberButton.getActivity()).isSameAs(testActivity); }
@Test(expected = IllegalStateException.class) public void getActivity_whenContextIsNotActivity_shouldThrowException() { final ContextThemeWrapper wrapper = new ContextThemeWrapper(RuntimeEnvironment.application, 0); UberButton uberButton = new UberButton(wrapper, null, 0, 0) { }; uberButton.getActivity(); }