Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

test if a button starts a new activity in android junit (pref without robotium)?

Tags:

android

junit

I cant find any good help on this. I have a simple activity with just a few buttons on and I need to test if they re-direct to the correct new page (activity).

public void testButton() {
         button.requestFocus();
         button.performClick();

      }

I really have no idea beyond that. The tutorials are all very unhelpful in doing this :/

like image 525
user1212520 Avatar asked Feb 23 '12 00:02

user1212520


2 Answers

You need ActivityMonitor, it helps you moniotor newly opened activity during instrumentation, check out the pseudo code below:

public void testOpenNextActivity() {
  // register next activity that need to be monitored.
  ActivityMonitor activityMonitor = getInstrumentation().addMonitor(NextActivity.class.getName(), null, false);

  // open current activity.
  MyActivity myActivity = getActivity();
  final Button button = (Button) myActivity.findViewById(com.company.R.id.open_next_activity);
  myActivity.runOnUiThread(new Runnable() {
    @Override
    public void run() {
      // click button and open next activity.
      button.performClick();
    }
  });

  //Watch for the timeout
  //example values 5000 if in ms, or 5 if it's in seconds.
  NextActivity nextActivity = getInstrumentation().waitForMonitorWithTimeout(activityMonitor, 5000);
  // next activity is opened and captured.
  assertNotNull(nextActivity);
  nextActivity .finish();
}
like image 168
yorkw Avatar answered Nov 04 '22 02:11

yorkw


NextActivity nextActivity = getInstrumentation().waitForMonitorWithTimeout(activityMonitor, 5);

The parameter 5 which is mentioned in above answer's method is in milliseconds not in seconds. So if it is 5, sometimes testcase get failed Because in 5 milliseconds it can't load the next activity. So 5000 or 10000 milliseconds will definitely work better. In documentation they have given it in seconds But in fact it is in milliseconds. So following method will work better than above method.

NextActivity nextActivity = getInstrumentation().waitForMonitorWithTimeout(activityMonitor, 10000);
like image 34
Rohit Haval Avatar answered Nov 04 '22 02:11

Rohit Haval