mardi 23 mai 2017

How can I test an interface implemented by an Activity which is used by a fragment?

I have an Activity that contains two fragments. One fragment has a EditText and a Button; when the button is clicked, a callback is invoked with the text from the edit box:

// Not showing implementation of onCreateView()
class HelloEditFragment extends Fragment implements View.OnClickListener {
  interface OnListener {
    void onValue(String value);
  }

  private OnListener mListener;

  public void onAttach(Context context) {
    mListener = (OnListener) context;
  }

  public void onClick(View v) {
    mListener.onValue(mEditText.getText().toString();
  }
}

My Activity implements OnListener:

class HelloActivity extends Activity implements HelloEditFragment.OnListener {
  public void onValue(String value) {
    // ...
  }
}

So far my test looks like this:

@RunWith (AndroidJUnit4.class)
public class HelloEditFragmentTest {

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

  @Test
  public void testActivity () {
    onView (withId (R.id.edit_text_hello_edit)).perform (typeText ("hello"));
    onView (withId (R.id.button_hello_edit)).perform (click ());
    // Now what?
  }
}

How can I check that the onValue() callback is called when the button in the fragment is clicked? Thanks,

Aucun commentaire:

Enregistrer un commentaire