Android,Espresso。如何检查软键盘是否被查看?
问题描述:
我有EditText和按钮(在EditText下)的屏幕。要求是显示软键盘时必须在按钮下。是否可以编写Espresso单元测试(或者anoter测试)来检查?Android,Espresso。如何检查软键盘是否被查看?
答
Android键盘是系统的一部分,而不是你的应用程序,所以意式咖啡在这里是不够的。
我在我的测试活动创造了以下布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.masta.testespressoapplication.MainActivity">
<EditText
android:id="@+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="TEST" />
</RelativeLayout>
如果你想只用咖啡肮脏的解决办法是:
@Test
public void checkButtonVisibilty2() throws Exception {
onView(withId(R.id.edittext)).perform(click());
try {
onView(withId(R.id.button)).perform(click());
throw new RuntimeException("Button was there! Test failed!");
} catch (PerformException e) {
}
}
此测试将尝试点击该按钮,它会抛出一个PerformException异常,因为它实际上会点击Softkeyboard - 这是不允许的。 但我不会推荐这种方式,这是相当滥用espresso框架。
溶液中的好一点恕我直言,是采用了android用户界面的Automator:
@Test
public void checkButtonVisibilty() throws Exception {
onView(allOf(withId(R.id.edittext), isDisplayed())).perform(click());
UiDevice mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
UiObject button = mDevice.findObject(new UiSelector().resourceId("com.example.masta.testespressoapplication:id/button"));
if (button.exists()) {
throw new RuntimeException("Button is visible! Test failed!");
}
}
本采用Android UI的Automator尝试获取按钮UI元素并检查它是否在当前屏幕中存在。 (更换包装,标识中的“RESOURCEID”与那些对你的情况下调用)
的Android UI的Automator u需要这个额外的gradle这个进口:
// Set this dependency to build and run UI Automator tests
androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.2'
androidTestCompile 'com.android.support:support-annotations:25.2.0'
一个总体思路:这种测试似乎非常容易出错,因为你没有真正的软键盘控制和它的外观,所以我会谨慎使用它。
我的回答是否帮助您解决问题? – stamanuel
不是没有帮助。因为当按钮可见时你的测试通过。但我只需要在以下情况下测试合格:按钮可见并且按钮的底部边界位于软键盘上方。 – Alexei
好的,你的意思是测试通过,但键盘略微超过按钮?这是因为android espresso具有90%的可见性规则(=如果视图项目的90%可见,则测试通过)。你可以覆盖它,然后按钮必须具有100%的可视性 – stamanuel