0

I write test in Espresso to test MyFragment. OK.

A write to test method that need to call custom method customUpdate() in MyFragment:

@Rule
    public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(MainActivity.class, true, false);

 @Before
    public void init() {
        mActivityRule.launchActivity(intent);

        // Here forward to MyFragment
        onView(withId(R.id.myTextView)).perform(click());
    }

     @Test
     public void searchAddFavorite() {
       // update column in db 
       MyService.updateColumn(context, 123, Profile.MY_COLUMN_NAME, false);

       // here need to call fragment custom method customUpdate()  

      onView(withId(R.id.searchView)).perform(click());
    }

Custom method in fragment (MyFragment) change cursor.

private void customUpdate() {
    cursor = MyService.getCursor(context, someFilter, true);
    contactAdapter.changeCursor(cursor);
}

How I can do this?

Bartek Lipinski
  • 30,698
  • 10
  • 94
  • 132
Alexei
  • 14,350
  • 37
  • 121
  • 240

1 Answers1

1

The answer is pretty simple: You need to obtain the instance of fragment that is in your activity and call the method.

And how you can do that, depends mostly on the way you're adding your fragment in the activity. Are you using a tag during the transaction? If not, you probably should. It will provide you with the easiest way to obtain the instance. If you don't know how to do that check this.

If you use tag yourTag, then you can do something like that:

@Test
public void searchAddFavorite() {
    // update column in db 
    MyService.updateColumn(context, 123, Profile.MY_COLUMN_NAME, false);

    MyFragment fragment = (MyFragment) mActivityRule.getActivity()
                                .getSupportFragmentManager().findFragmentByTag("yourTag");  
    fragment.customUpdate();

    onView(withId(R.id.searchView)).perform(click());
}

That said, for me it doesn't really sound like you should be performing an UI test here. It seems like you should look into regular unit tests.

Community
  • 1
  • 1
Bartek Lipinski
  • 30,698
  • 10
  • 94
  • 132