2

How to use espresso idling resource if long running task is started in Activity's onCreate ?

I have created a custom IdlingResource and it is working fine if the long async method call is triggered by click event, but breaks whenever the it is called in Acitivty's onCreate method.

Example:

public void onBtnClick(){
    setIdle(true); // This works fine, our tests wait until setIdle(false) is called
    doSomeBackgroundTask(); 
}

public void onDone(){
    setResourceIdle(false);
    setIdle(false);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setIdle(true); // This doesn't work, our tests won't wait
    doSomeBackgroundTask(); 
}

Any ideas to overcome this situation?

Rajesh Batth
  • 1,672
  • 2
  • 19
  • 23

1 Answers1

4

Try registering your idlingResource before activity onCreate.

Simple @Before method should be enough.

You can also implement your own ActivityRule and override beforeActivityLaunched() method if you are using espresso-rules

Or if you want to execute any code before Application oncreate you need to implement your own testrunner and override callApplicationOnCreate()

Example of the test rule is shown here: ActivityTestRule - how to call code before Application's onCreate

Community
  • 1
  • 1
Be_Negative
  • 4,892
  • 1
  • 30
  • 33
  • @before is getting called after onCreate, so how can i register ? – Rajesh Batth Jun 23 '15 at 09:57
  • activity onCreate is called when activity is launched. If you are using espresso-rules, launch activity manually in your tests by passing the false boolean into the rule constructor and call `launchActivity(Intent intent)` method `ActivityTestRule rule = new ActivityTestRule(MyActivity.class, false, false); rule.launchActivity(startIntent)` . – Be_Negative Jun 23 '15 at 12:04
  • I have made the activity to implement the Listener which will update me on on task is done, so without the instance of activity i can't register Idling resource. What i want is reference of activity before onCreate is called. – Rajesh Batth Jun 23 '15 at 14:15
  • If you want to keep your current implementation you can look into implementing your own test runner and overriding ``callActivityOnCreate()`` and get reference of the activity from there. I described how to implement such test runner in the answer. – Be_Negative Jun 28 '15 at 19:50
  • @RajeshBatth any luck with this solution? I have exactly the same problem as You had. You cannot pass anything custom to your own JUnitRunner so I can't think of a way to use it. Why is it so hard to achieve something as simple as running two lines of code before onCreate method from activity... – M Tomczynski Feb 17 '17 at 09:44