Albert Robert
Albert Robert

Reputation: 61

Mock the onCreate of an activity when initialized with Espresso ActivityTestRule without using Dagger

I try to initialize my activity with espresso and mock the onCreate but did not find a good solution without adding Dagger to my project:

@Rule
public ActivityTestRule<MyActivity> mActivityRule = new ActivityTestRule<>(MyActivity.class);

I tried also to create a custom rule but this did not help since I don't have access to mock the activity just right before it is createa... Only after the creation, but the onCreate at that time is already called.

public class MyCustomRule<A extends MyActivity> extends ActivityTestRule<A> { ....
  @Override
  protected void beforeActivityLaunched(){super.beforeActivityLaunched();}
  @Override
  protected Intent getActivityIntent() {...}
  @Override
  protected void afterActivityLaunched() {...}
  @Override
  protected void afterActivityFinished() {...}
}

Upvotes: 1

Views: 843

Answers (1)

Albert Robert
Albert Robert

Reputation: 61

I found a solution to the problem I had, by using the SingleActivityFactory:

private SingleActivityFactory<MyActivity> injectedFactory = new SingleActivityFactory<MyActivity>(MyActivity.class) {
 @Override
 protected MyActivity create(Intent intent) {
    MyActivity activity = new MockMyActivity();
    return activity;
 }
};

And use this to create the Rule

@Rule
public ActivityTestRule<MyActivity> mActivityRule = new ActivityTestRule<>(injectedFactory, false, true);

Where your MockMyActivity.class would look something like this:

public class MockMyActivity extends MyActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {  
      super.onCreate(savedInstanceState);
      // you can add some of your logic here
    }

    @Override
    protected MyFragment findOrCreateViewFragment() {
      MyFragment myFragment = (MyFragment) getSupportFragmentManager().findFragmentById(R.id.contentFrame);
      if (myFragment == null) {
         //spy-mock your fragment
         myFragment = spy(new MyFragment());
         // ex do not load data from the web service
         doNothing().when(myFragment).callLoadMyService();

        ActivityUtils.addFragmentToActivity(getSupportFragmentManager(), myFragment, R.id.contentFrame);
      }
      return myFragment;
}

Upvotes: 2

Related Questions