android 使用espresso测试软键盘是否可见

wfauudbj  于 2023-04-04  发布在  Android
关注(0)|答案(6)|浏览(190)

我想测试Activity调用onCreate()和onResume()时的键盘可见性。
如何测试使用espresso时是否显示键盘?

zysjyyx4

zysjyyx41#

我知道,这个问题已经很老了,但是它没有任何公认的答案。在我们的UI测试中,我们使用这个方法,它使用了一些shell命令:

/**
 * This method works like a charm
 *
 * SAMPLE CMD OUTPUT:
 * mShowRequested=true mShowExplicitlyRequested=true mShowForced=false mInputShown=true
 */
fun isKeyboardOpenedShellCheck(): Boolean {
    val checkKeyboardCmd = "dumpsys input_method | grep mInputShown"

    try {
        return UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
            .executeShellCommand(checkKeyboardCmd).contains("mInputShown=true")
    } catch (e: IOException) {
        throw RuntimeException("Keyboard check failed", e)
    }
}

Hope这对某人有用

4ioopgfo

4ioopgfo2#

fun isKeyboardShown(): Boolean {
    val inputMethodManager = InstrumentationRegistry.getInstrumentation().targetContext.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    return inputMethodManager.isAcceptingText
}

发现于Google groups

rqmkfv5c

rqmkfv5c3#

另一个技巧可以是检查一个视图的可见性,你知道当键盘显示时会被覆盖。不要忘记考虑动画...
使用espresso和hamcrest对NOT matcher进行仪器测试,例如:

//make sure keyboard is visible by clicking on an edit text component
    ViewInteraction v = onView(withId(R.id.editText));
    ViewInteraction v2 = onView(withId(R.id.componentVisibleBeforeKeyboardIsShown));
    v2.check(matches(isDisplayed()));
    v.perform(click());
    //add a small delay because of the showing keyboard animation
    SystemClock.sleep(500);
    v2.check(matches(not(isDisplayed())));
    hideKeyboardMethod();
    //add a small delay because of the hiding keyboard animation
    SystemClock.sleep(500);
    v2.check(matches(isDisplayed()));
2lpgd968

2lpgd9684#

这对我有用。

private boolean isSoftKeyboardShown() {
    final InputMethodManager imm = (InputMethodManager) getActivityInstance()
           .getSystemService(Context.INPUT_METHOD_SERVICE);

    return imm.isAcceptingText();
}

@igork的答案的Java版本。

e0uiprwp

e0uiprwp5#

这个方法对我很有效

val isKeyboardOpened: Boolean
    get() {
        for (window in InstrumentationRegistry.getInstrumentation().uiAutomation.windows) {
            if (window.type == AccessibilityWindowInfo.TYPE_INPUT_METHOD) {
                return true
            }
        }
        return false
    }
6pp0gazn

6pp0gazn6#

fun checkIsKeyboardDisplayed(expectedIsDisplayed: Boolean) {
  val actualIsDisplayed: Boolean
  val checkKeyboardCmd = "dumpsys input_method | grep mInputShown"
  try {
    actualIsDisplayed = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
      .executeShellCommand(checkKeyboardCmd).contains("mInputShown=true")
  } catch (e: IOException) {
    throw RuntimeException("Keyboard check failed", e)
  }
  Assert.assertTrue(actualIsDisplayed == expectedIsDisplayed)
}`enter code here`

相关问题