使用UiAutomator测试Snackbar,有办法吗?

时间:2017-02-08 13:49:41

标签: java android user-interface uiautomator android-uiautomator

我开始在Android上学习UIAutomator。 我创建了一个简单的poc项目,里面有很少的元素:一个按钮和一个editText。 行为很简单: 当我按下按钮时,editText中写入的消息将显示在snackBar中。

现在我想做两个简单的测试:

  1. 查看小吃栏是否正确显示
  2. 查看editTest消息是否为 在小吃栏中正确报告
  3. 对于第一点我用这种方式做了:

     @Test
    public void pressEmailButton() throws UiObjectNotFoundException {
        mDevice.findObject( By.res(POC_PACKAGE,"fab") ).click();
    
        // wait for the snackBar appear
        UiObject snackBar2 = new UiObject (new UiSelector().text("Send"));
    
        // Verify the snackBarIsShowed is displayed in the Ui
        assertTrue("Timeout while snackbar",  snackBar2.waitForExists(1000));
    }
    

    那就是我正在观看小吃店检查小吃店是否正确打开的动作。有更好的方法吗?通过这种方式,如果有更多元素以与快餐栏相同的方式命名,我将遇到问题

    对于第二点,我找不到测试它的方法。 我只能使用uiAutomator而不是Espresso:)

    感谢大家:)

1 个答案:

答案 0 :(得分:0)

我刚刚尝试了一个新的android项目:我在主布局中有一个Button,并按下按钮点击快餐栏,如下所示:

button = (Button) findViewById(R.id.button);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
        View parentLayout = findViewById(R.id.root_layout);
        Snackbar.make(parentLayout, "Snackbar Text", Snackbar.LENGTH_LONG)
                .show();
        }
});

在我的测试中,我然后测试它:

//With espresso:
onView(withId(R.id.button)).perform(click()); //click the button
onView(withText("Snackbar Text")).check(matches(isDisplayed()));

与使用UI Automator相同:

UiDevice mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
UiObject snackbarTextView = mDevice.findObject(new UiSelector().text("Snackbar Text"));

if(!snackbarTextView.getText().equals("Snackbar Text")) {
    throw new RuntimeException("No snackbar!");
}

两项测试都运行得很好! 选择Snackbar文本的另一种方法是通过资源ID,如下所示:

//replace the package name in the next line with your package name
UiObject snackbarTextView = mDevice.findObject(new UiSelector().resourceId("com.example.testespressoapplication:id/snackbar_text"));

你做它的方式也有效但不推荐使用,所以我不会使用它,正如文档所说:

* @deprecated Use {@link UiDevice#findObject(UiSelector)} instead. This version hides
* UiObject's dependency on UiDevice and is prone to misuse.