Android,浓缩咖啡.检查如何软键盘正在查看



我的屏幕带有EditText和button(在EditText下)。要求是当显示软键盘时,它必须在按钮下。是否可以编写浓缩咖啡单元测试(或Anoter测试)来检查此问题?

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) {
    }
}

此测试将尝试单击该按钮,该按钮会引发性能,因为它实际上会单击软键板 - 不允许。但是我不建议这样,这完全是对浓缩咖啡框架的滥用。

一个更好的恕我直言的解决方案将使用Android UI 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元素并检查当前屏幕中是否存在。(用案件替换"资源ID"呼叫中的软件包和ID)

对于Android UI Automator,您需要此额外的Gradle Imports:

// 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'

一般的想法:这种测试似乎很容易出错,因为您对软键盘没有真正的控制以及它的外观,因此我会谨慎使用它。

最新更新