Home » Android » android – How do I detect with Robolectric that onBackPressed is called programmatically?

android – How do I detect with Robolectric that onBackPressed is called programmatically?

Posted by: admin June 15, 2020 Leave a comment

Questions:

I am using Robolectric to do unit tests. In my app I have a method that programmatically calls onBackPressed. However I do not know how to test whether this method is properly executed with RoboLectric. I have already tested it on a device and the method works fine. But now: how do I validate this with Robolectric?

How to&Answers:
activity.initialize();
Button button = (Button) activity.findViewById(R.id.button_with_on_back_pressed_called);
ShadowButton buttonShadow = (ShadowButton) Robolectric.shadowOf(button);
OnClickListener onClickListener = buttonShadow.getOnClickListener();
onClickListener.onClick(button);

ShadowActivity activityShadow = Robolectric.shadowOf(activity);
assertTrue(activityShadow.isFinishing());