Espresso - typeText not working

2019-04-22 18:26发布

问题:

I'm trying to type some text inside an EditText:


    public void testSearch() {
          onView(withId(R.id.titleInput)).perform(typeText("Engineer"));
          onView(withId(R.id.titleInput)).check(matches(withText("Engineer")));
    }

I see the EditText is getting focus, but nothing happens. No text is typed.
I tried this on a phone and an emulator - same result.

回答1:

Looks like I figured out the issue. It had to do with hardware vs software keyboard.

For Emulators:

Go to Settings -> Language & Input -> switch the Default Input to Sample Soft Keyboard.

For Phones:

Install a software keyboard from the Play store and switch to it. It appears that the native keyboards of some phones do not work.

It works now.



回答2:

If the EditText does not has the focus yet, you should click on it first. If this solves your problem, then there is no bug.

onView(withId(R.id.titleInput)).perform(click()).perform(typeText("Engineer"));


回答3:

Had the same issue using Espresso 2. As a workaround I'm using replaceText instead of typeText.

public void testSearch() {
      onView(withId(R.id.titleInput)).perform(click(), replaceText("Engineer"));
      onView(withId(R.id.titleInput)).check(matches(withText("Engineer")));
}


回答4:

You can bypass the problem by calling setText on the EditText.

   final EditText titleInput = (EditText) activity.findViewById(R.id.titleInput);
   getInstrumentation().runOnMainSync(new Runnable() {
        public void run() {
            titleInput.setText("Engineer");
        }
    });


回答5:

You can include it with in the code like this,

onView(withId(R.id.titleInput)).perform(click(), replaceText("Engineer"), closeSoftKeyboard() );



回答6:

If you're using Genymotion, you may need to switch the default keyboard in Genymotion Configuration (it's an app on the emulator).

  1. Go to Apps -> Genymotion Configuration -> Keyboard -> Virtual keyboard (click "Yes" when you're prompted to reboot)

NOTE: These changes do not persist after you close the emulator. You will need to set this every time you start the emulator.



回答7:

I fixed this issue by setting layout_height="wrap_content" on the View I wanted to click(). Maybe it can help someone here.