要检查键盘是否隐藏,可以使用Android的InputMethodManager类的isAcceptingText()方法。
以下是一个使用Espresso进行UI测试的示例代码:
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import androidx.test.espresso.UiController;
import androidx.test.espresso.ViewAction;
import androidx.test.espresso.matcher.ViewMatchers;
import androidx.test.rule.ActivityTestRule;
import androidx.test.runner.AndroidJUnit4;
import org.hamcrest.Matcher;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.action.ViewActions.closeSoftKeyboard;
import static androidx.test.espresso.action.ViewActions.typeText;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static org.hamcrest.Matchers.not;
@RunWith(AndroidJUnit4.class)
public class KeyboardTest {
@Rule
public ActivityTestRule activityRule = new ActivityTestRule<>(MainActivity.class);
@Test
public void testKeyboardHidden() {
onView(ViewMatchers.withId(R.id.editText)).perform(typeText("Test"), closeSoftKeyboard());
onView(ViewMatchers.withId(R.id.button)).perform(click());
onView(ViewMatchers.withId(R.id.editText)).check(matches(not(isKeyboardShown())));
}
private static Matcher isKeyboardShown() {
return new Matcher() {
@Override
public boolean matches(Object item) {
if (item instanceof View) {
View view = (View) item;
InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
return imm.isAcceptingText();
}
return false;
}
@Override
public void describeMismatch(Object item, Description mismatchDescription) {
mismatchDescription.appendText("Keyboard is shown");
}
@Override
public void _dont_implement_Matcher___instead_extend_BaseMatcher_() {
}
@Override
public void describeTo(Description description) {
description.appendText("Keyboard is hidden");
}
};
}
}
在上面的示例中,我们首先在EditText上输入一些文本,然后关闭键盘。然后,我们点击一个按钮触发一些操作。最后,我们使用自定义的isKeyboardShown()方法来检查键盘是否隐藏,然后使用Espresso的matches()方法进行断言。如果键盘隐藏,断言将成功通过。