1

I am trying to use idling resources in my test following this tutorial.

The problem is that the code to be tested already runs in the onCreate() method.

In this (old) question it is suggested to register the idling resource in an @Before annotated method, but that does not solve the problem since we still need an instance of the activity for the registering:

private ActivityScenario<MyActivity> scenario;
private IdlingResource myIdlingResource;

@Before
public void setUp() {
    scenario = ActivityScenario.launch(MyActivity.class); // all the code in onCreate() (and also onStart() and onResume()) will run now and idling resource will be null
    scenario.onActivity(activity -> { 
        // now we have a reference to the activity under test but it is already too late; 
        // this method can not be called before the activity is launched
        myIdlingResource= activity.getIdlingResource();
        IdlingRegistry.getInstance().register(myIdlingResource);
    });
}

@Test
public void test() {
    // assert stuff that happens when activity is created
}

How can I use idling resources in this scenario?

flauschtrud
  • 690
  • 7
  • 23

1 Answers1

0

The problem is that both the activity under test as the test need to use the same idling resource.

I finally came up with a solution using dependency injection, since I already use Dagger in my project and have also used it to inject mock dependencies for testing purposes.

I inject a real idling resource in my test module:

@Module
public class MyMockModule {

   @Provides
   @Singleton
   CountingIdlingResource myIdlingResource(){
      return new CountingIdlingResource("MyIdleStuff");
   }
}

And I inject a null idling resource for the production code, to make sure that the idling resource code is not called in production (would be better here to have a custom implementation of IdlingResource which just does nothing):

@Module
public class MyModule {

   @Provides
   @Nullable
   @Singleton
   CountingIdlingResource myIdlingResource(){
      return null;
   }
}

It still feels a bit weird to have to add to production code in order to make tests work and to use mocks for production and real implementations for testing, but at least this makes my tests work (without having to resort to drastic means like Thread.sleep()...

flauschtrud
  • 690
  • 7
  • 23