2017-02-08 170 views
3

我开始在Android上学习UIAutomator。 我创建了一个简单的poc项目,里面有很少的元素:一个按钮和一个editText。 这个行为很简单: 当我推动botton时,在editText中写的消息出现在一个snackBar中。用UiAutomator测试Snackbar,有没有办法?

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

  1. 看是否小吃吧正确显示
  2. 看到,如果editTest消息 正确的小吃吧报告

对于点一个我以这种方式完成:

@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 :)

感谢大家:)

+0

可以请你发布你的活动图像或布局heirarchy?不是它出现'uiautomatorviewer'小吃店? – Rilwan

+0

是否必须是uiautomator或者您是否也可以使用espresso检查? – stamanuel

回答

0

我只是想在一个新的Android项目:我在主要布局一个按钮和显示按钮点击小吃吧像这样:

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!"); 
} 

两个测试都可以正常工作! 另一个选择小吃吧文本的方式是通过资源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. 
相关问题