gpt4 book ai didi

java - 用 UiAutomator 测试 Snackbar,有办法吗?

转载 作者:太空宇宙 更新时间:2023-11-03 11:01:22 25 4
gpt4 key购买 nike

我开始研究 Android 上的 UIAutomator。我创建了一个简单的 poc 项目,里面只有很少的元素:一个按钮和一个 editText。行为非常简单:当我按下按钮时,在 editText 中写入的消息会出现在 snackBar 中。

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

  1. 查看 snackbar 是否正确显示
  2. 查看 editTest 消息是否为在 snackbar 中正确报告

对于第一点,我是这样做的:

 @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));
}

也就是我正在观察 snackbar 的 Action ,以检查 snackbar 是否正确打开。有更好的方法吗?这样,如果有更多元素以与 snackbar 的 Action 相同的方式命名,我就会遇到问题

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

感谢大家:)

最佳答案

我刚刚在一个新的 android 项目中尝试过:我在主布局中有一个 Button 并在按钮单击时显示 snackbar,如下所示:

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.

关于java - 用 UiAutomator 测试 Snackbar,有办法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42114931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com