下面列出了android.view.MotionEvent.PointerCoords#android.support.test.uiautomator.UiObjectNotFoundException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void allowPermissionsIfNeeded() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
sleep(PERMISSIONS_DIALOG_DELAY);
UiDevice device = UiDevice.getInstance(getInstrumentation());
UiSelector selector = new UiSelector()
.clickable(true)
.checkable(false)
.index(GRANT_BUTTON_INDEX);
UiObject allowPermissions = device.findObject(selector);
if (allowPermissions.exists()) {
allowPermissions.click();
}
}
} catch (UiObjectNotFoundException e) {
System.out.println("There is no permissions dialog to interact with");
}
}
public void allowPermissionsIfNeeded() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
sleep(PERMISSIONS_DIALOG_DELAY);
UiDevice device = UiDevice.getInstance(getInstrumentation());
UiObject allowPermissions = device.findObject(new UiSelector()
.clickable(true)
.checkable(false)
.index(GRANT_BUTTON_INDEX));
if (allowPermissions.exists()) {
allowPermissions.click();
}
}
} catch (UiObjectNotFoundException e) {
System.out.println("There is no permissions dialog to interact with");
}
}
@Test
public void doOrientationTestForFixedAndManualProgressWithIcon() throws RemoteException, InterruptedException, UiObjectNotFoundException {
doInitialSetUpForFixedAndManualProgressTest();
mDevice.setOrientationLeft();
mDevice.waitForIdle();
Espresso.onView(withId(R.id.button)).perform(scrollTo());
Thread.sleep(Constants.MORPH_DURATION);
checkManualProgressAmount();
Utils.doProgress(doProgressText);
Utils.doProgress(doProgressText);
Thread.sleep(Constants.MORPH_DURATION);
checkFixedAndManualProgressCompleteWithIcon();
mDevice.setOrientationNatural();
Thread.sleep(ORIENTATION_PERSIST_TIME);
Utils.clickAndShowIdleState(idleStateText, R.id.circularButton2);
Utils.clickAndShowIdleState(idleStateText, R.id.circularButton3);
Thread.sleep(Constants.MORPH_DURATION);
}
/**
*
*/
private void testIfSlide( int index ){
if ( index <= 0 ) throw new IllegalArgumentException("Bad parameter for index");
try {
UiObject title = mDevice.findObject(
new UiSelector().resourceId(PACKAGE_APP_PATH + ":id/title")
);
UiObject description = mDevice.findObject(
new UiSelector().resourceId(PACKAGE_APP_PATH + ":id/description")
);
UiObject next = mDevice.findObject(
new UiSelector().resourceId(PACKAGE_APP_PATH + ":id/skip")
);
assertEquals(sTitles[index - 1], title.getText());
assertEquals(sSummaries[index-1], description.getText());
assertTrue(next.exists());
} catch ( UiObjectNotFoundException uonfe ){
uonfe.printStackTrace();
fail(uonfe.getMessage() );
}
}
/**
* Opens the standalone mode dialog
*/
private void openStandaloneModeDialog(){
try {
// Display the pop-up
UiObject menu = mDevice.findObject(
new UiSelector().className("android.widget.ImageView")
//.description("Plus d'options") // FIXME Raw french string
.description("Autres options") // WARNING FIXME French string used, use instead system R values
);
menu.click();
UiObject menuItem = mDevice.findObject(
new UiSelector().className("android.widget.TextView").text(InstrumentationRegistry.getTargetContext().getString(R.string.action_standalone))
);
menuItem.click();
} catch ( UiObjectNotFoundException uinfe ){
uinfe.printStackTrace();
fail(uinfe.getMessage());
}
}
public boolean handleAnr() {
UiObject window = sDevice.findObject(new UiSelector()
.className("com.android.server.am.AppNotRespondingDialog"));
String errorText = null;
if (window.exists()) {
try {
errorText = window.getText();
} catch (UiObjectNotFoundException e) {
Log.e(TAG, "dialog gone?", e);
}
onAnrDetected(errorText);
postHandler();
return true; // triggered
}
return false; // no trigger
}
public boolean handleAnr2() {
UiObject window = sDevice.findObject(new UiSelector().packageName("android")
.textContains("isn't responding."));
if (!window.exists()) {
window = sDevice.findObject(new UiSelector().packageName("android")
.textContains("沒有回應"));
}
if (window.exists()) {
String errorText = null;
try {
errorText = window.getText();
} catch (UiObjectNotFoundException e) {
Log.e(TAG, "dialog gone?", e);
}
onAnrDetected(errorText);
postHandler();
return true; // triggered
}
return false; // no trigger
}
public boolean handleCrash() {
UiObject window = sDevice.findObject(new UiSelector()
.className("com.android.server.am.AppErrorDialog"));
if (window.exists()) {
String errorText = null;
try {
errorText = window.getText();
} catch (UiObjectNotFoundException e) {
Log.e(TAG, "dialog gone?", e);
}
onCrashDetected(errorText);
postHandler();
return true; // triggered
}
return false; // no trigger
}
public static void inputRandomTextToEditText() {
UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
UiObject edit = null;
int i = 0;
do {
edit = null;
edit = device.findObject(new UiSelector().className("android.widget.EditText").instance(i++));
if (edit != null && edit.exists()) {
try {
Random rand = new Random();
String text = Config.RANDOM_TEXT[rand.nextInt(Config.RANDOM_TEXT.length - 1)];
edit.setText(text);
} catch (UiObjectNotFoundException e) {
// Don't worry
}
}
} while (edit != null && edit.exists());
}
@Test
public void it_should_be_possible_to_open_add_new_item_window() throws UiObjectNotFoundException {
mDevice.findObject(
new UiSelector()
.descriptionContains("Add New Stock Button")
).click();
UiObject2 result = mDevice.findObject(
By.res(TARGET_PACKAGE, "portfolio_addnew_symbol")
);
assertThat(result.getText(), is("GOOG"));
}
@Test
public void it_should_be_possible_to_open_add_new_item_window() throws UiObjectNotFoundException {
mDevice.findObject(
new UiSelector()
.descriptionContains("Add New Stock Button")
).click();
UiObject2 result = mDevice.findObject(
By.res(TARGET_PACKAGE, "portfolio_addnew_symbol")
);
assertThat(result.getText(), is("GOOG"));
}
public boolean pinch(String direction, float percent, int steps) throws UiObjectNotFoundException {
if (direction.equals("in")) {
element.pinchOpen(percent, steps);
} else if (direction.equals("out")) {
element.pinchClose(percent, steps);
}
return true;
}
/**
* Searches for child UI element within the constraints of this UiSelector selector. It looks for any child matching the childPattern argument that has a child UI element anywhere within its sub hierarchy that has a text attribute equal to text. The returned UiObject will point at the childPattern instance that matched the search and not at the identifying child element that matched the text attribute.
*
* @param collection Selector of UiCollection or UiScrollable.
* @param text String of the identifying child contents of of the childPattern
* @param child UiSelector selector of the child pattern to match and return
* @return A string ID represent the returned UiObject.
*/
@Override
public String childByText(Selector collection, Selector child, String text) throws UiObjectNotFoundException {
UiObject obj;
if (exist(collection) && objInfo(collection).isScrollable()) {
obj = new UiScrollable(collection.toUiSelector()).getChildByText(child.toUiSelector(), text);
} else {
obj = new UiCollection(collection.toUiSelector()).getChildByText(child.toUiSelector(), text);
}
return addUiObject(obj);
}
@Test
@Ignore
@NeedsMockWebServer(setupMethod = "queueNetworkRequest")
public void shouldDisplayGeocachesFromServer() throws UiObjectNotFoundException {
UiAutomatorUtils.allowPermissionsIfNeeded(device);
// Swipe the refresh view
onView(withId(R.id.cachelist_swiperefresh)).perform(swipeDown());
}
public static void allowPermissionsIfNeeded(UiDevice device) {
if (Build.VERSION.SDK_INT >= 23) {
UiObject allowPermissions = device.findObject(new UiSelector().text(TEXT_ALLOW));
if (allowPermissions.exists()) {
try {
allowPermissions.click();
} catch (UiObjectNotFoundException ignored) {
}
}
}
}
/**
* Check if view exists. This methods performs a waitForExists(long) with zero timeout. This basically returns immediately whether the view represented by this UiObject exists or not.
*
* @param obj the id of ui object.
* @return true if the view represented by this UiObject does exist
*/
@Override
public boolean exist(String obj) {
try {
return getUiObject(obj).exists();
} catch (UiObjectNotFoundException e) {
return false;
}
}
/**
* Tests if the snack bar is displayed when a point has been clicked
*
* <i>If a point with (x,y) coordinates has been chosen, a snackbar with the following text has to be displayed "Click X = x / Y = y"</i>
*/
@Test
public void snackBarNewPoint(){
l(this, "@Test snackBarNewPoint");
final int X = 500;
final int Y = 600;
final String S = "Click X = " + X + " / Y = " + Y;
try {
// Wait for the activity because Espresso is too fast
w(5000);
// Click on the dedicated screen to make a new point
clickAt(X, Y);
// Get the snack bar
UiObject snackBar = mDevice.findObject(
new UiSelector().resourceId(PACKAGE_APP_PATH + ":id/snackbar_text")
);
w(2000);
assertTrue(snackBar.exists());
assertEquals( S, snackBar.getText());
} catch ( UiObjectNotFoundException uonfe ){
uonfe.printStackTrace();
fail( uonfe.getMessage() );
}
}
/**
* @param text - The text of the field to get
* @param newValue - The new value
*/
private void resetFieldWithText( String text, String newValue ){
if ( text == null || text.length() <= 0 ){
fail("Wrong test");
}
try {
// Display the dialog
UiObject field = mDevice.findObject(
new UiSelector()
.className("android.widget.TextView")
.packageName(PACKAGE_APP_PATH)
.resourceId("android:id/title")
.text(text)
);
field.click();
// Change the value
field = mDevice.findObject(
new UiSelector()
.className("android.widget.EditText")
.packageName(PACKAGE_APP_PATH)
.resourceId("android:id/edit")
);
field.setText(newValue);
// Confirm
UiObject button = mDevice.findObject(
new UiSelector()
.className("android.widget.Button")
.packageName(PACKAGE_APP_PATH)
.resourceId("android:id/button1")
);
button.click();
} catch ( UiObjectNotFoundException uonfe ){
uonfe.printStackTrace();
fail(uonfe.getMessage());
}
}
private boolean swipe(UiObject2 item, String dir,float percent, int steps) throws UiObjectNotFoundException {
dir = dir.toLowerCase();
if ("u".equals(dir) || "up".equals(dir)) item.swipe(Direction.UP,percent,steps);
else if ("d".equals(dir) || "down".equals(dir)) item.swipe(Direction.DOWN,percent,steps);
else if ("l".equals(dir) || "left".equals(dir)) item.swipe(Direction.LEFT,percent,steps);
else if ("r".equals(dir) || "right".equals(dir)) item.swipe(Direction.RIGHT,percent,steps);
return true;
}
/**
* Tests the long clicks on the floating action button for SU grant in the arc menu
*
* <i>A long click on the button to use to get the SU grant should display a snackbar with an explain message</i>
*/
@Test
public void longClickOnArcMenuSuGrantItem(){
l(this, "@Test longClickOnArcMenuSuGrantItem");
String expectedString = InstrumentationRegistry.getTargetContext().getString(R.string.info_message_request_su);
try {
/*
* Display the floating action buttons in the arc menu
*/
UiObject arcMenu = mDevice.findObject(
new UiSelector().resourceId(PACKAGE_APP_PATH + ":id/fabAction")
);
arcMenu.click();
arcMenu.waitForExists(WAIT_FOR_EXISTS_TIMEOUT);
/*
* The floating action button
*/
UiObject fab = mDevice.findObject(
new UiSelector().resourceId(PACKAGE_APP_PATH+":id/fabRequestSuGrant")
);
fab.waitForExists(WAIT_FOR_EXISTS_TIMEOUT);
assertTrue(fab.isLongClickable());
fab.swipeLeft(100); //fab.longClick() makes clicks sometimes, so swipeLeft() is a trick to make always a longclick
UiObject snack = mDevice.findObject(
new UiSelector().resourceId(PACKAGE_APP_PATH + ":id/snackbar_text")
);
assertEquals(expectedString, snack.getText());
} catch ( UiObjectNotFoundException uonfe ){
uonfe.printStackTrace();
fail( uonfe.getMessage() );
}
}
/**
* Test if the switch changes (for the start type) modifies well the delay field
*
* <i>If the switch for the start type is ON, the delay field is enabled.</i>
* <i>If the switch for the start type is OFF, the delay field is disabled.</i>
*/
@Test
public void changeDelayOnSwitchChanges(){
l(this, "@Test changeDelayOnSwitchChanges");
try {
UiObject startSwitch = mDevice.findObject(
new UiSelector().resourceId(PACKAGE_APP_PATH + ":id/sTypeOfStartDelayed")
);
UiObject delayField = mDevice.findObject(
new UiSelector().resourceId(PACKAGE_APP_PATH + ":id/etDelay")
);
// Check and uncheck the switch
for ( int i = 1; i <= 2; i++ ) {
startSwitch.click();
if (startSwitch.isChecked()) {
assertTrue(delayField.isEnabled());
} else {
assertFalse(delayField.isEnabled());
}
}
} catch ( UiObjectNotFoundException uonfe ){
uonfe.printStackTrace();
fail( uonfe.getMessage() );
}
}
/**
* Test the start button without having defined clicks
*
* <i>If the button to start the click process is clicked, and no point has been defined, a snackbar with an error message has to be displayed</i>
*/
@Test
public void startButtonWithoutDefinedPoints(){
l(this, "@Test startButtonWithoutDefinedPoints");
try {
// Open the arc menu
UiObject arcMenu = mDevice.findObject(
new UiSelector().resourceId(PACKAGE_APP_PATH + ":id/fabAction")
);
arcMenu.click();
// Click on the button
UiObject startFab = mDevice.findObject(
new UiSelector().resourceId(PACKAGE_APP_PATH + ":id/fabStart")
);
startFab.click();
// Check the snackbar
UiObject snack = mDevice.findObject(
new UiSelector().resourceId(PACKAGE_APP_PATH + ":id/snackbar_text")
);
String expectedString = InstrumentationRegistry.getTargetContext().getString(R.string.error_message_no_click_defined);
assertEquals(expectedString, snack.getText());
} catch ( UiObjectNotFoundException uonfe ){
uonfe.printStackTrace();
fail( uonfe.getMessage() );
}
}
/**
* Test the button for selecting points
*
* <i>If the button to select points is clicked, the activity to select points have to be launched</i>
* <i>If in this activity we click on back, the main activity must be displayed and the previous activity finished</i>
*/
@Test
public void selectPointsButton(){
l(this, "@Test selectPointsButton");
try {
// Open the arc menu
UiObject arcMenu = mDevice.findObject(
new UiSelector().resourceId(PACKAGE_APP_PATH + ":id/fabAction")
);
arcMenu.click();
// Click on the button
UiObject selectPointsFab = mDevice.findObject(
new UiSelector().resourceId(PACKAGE_APP_PATH + ":id/fabSelectPoint")
);
selectPointsFab.click();
// UIAutomator seems to be useless about getting the current activity (deprecated methods)
// so check if the enw activity's layout is displayed
UiObject newActivityMainLayout = mDevice.findObject(
new UiSelector().resourceId(PACKAGE_APP_PATH + ":id/translucentMainView")
);
w(2000);
assertTrue(newActivityMainLayout.exists());
// Press back and check if we are in the previous activity (i.e. arc menu displayed)
mDevice.pressBack();
w(2000);
assertTrue(arcMenu.exists());
} catch ( UiObjectNotFoundException uonfe ){
uonfe.printStackTrace();
fail( uonfe.getMessage() );
}
}
/**
* Tests the import feature with its snackbar
*
* <i>If the configuration is imported in the JSON files, a snackbar with a good message is displayed</i>
*/
@Test
public void importConfig(){
l(this, "@Test importConfig");
try {
// Display the pop-up
UiObject menu = mDevice.findObject(
new UiSelector().className("android.widget.ImageView").description("Autres options") // FIXME Raw french string
);
menu.click();
UiObject submenu = mDevice.findObject(
new UiSelector().className("android.widget.TextView").text(InstrumentationRegistry.getTargetContext().getString(R.string.action_configuration))
);
submenu.click();
UiObject menuItem = mDevice.findObject(
new UiSelector().className("android.widget.TextView").text(InstrumentationRegistry.getTargetContext().getString(R.string.action_import))
);
menuItem.click();
// Check the snackbar
UiObject snackbar = mDevice.findObject(
new UiSelector().className("android.widget.TextView")
.resourceId(PACKAGE_APP_PATH + ":id/snackbar_text")
);
assertTrue(snackbar.exists());
assertEquals(InstrumentationRegistry.getTargetContext().getString(R.string.info_import_success), snackbar.getText());
} catch ( UiObjectNotFoundException uonfe ){
uonfe.printStackTrace();
fail(uonfe.getMessage());
}
}
/**
* Test the click on the button for the "clean points" feature
*
* <i>If the button to clean points is clicked, the list of points has to be cleaned</i>
* <i>If the button to clean points is clicked and no values has been changed, the values still remain the default ones</i>
*/
@Test
public void clickCleanPoints() {
l(this, "@Test clickCleanPoints");
try {
// Get the menu item
UiObject mi = mDevice.findObject(
new UiSelector().resourceId(PACKAGE_APP_PATH + ":id/action_clean_all")
);
w(5000); // If there is no wait, Espresso fails to get the floating action button
// Bind the list
fillSpinnerAsUser();
// Click on the menu item
mi.click();
// Check if the values have been made empty
// onView(withId(R.id.clickerActivityMainLayout)).perform(swipeUp());
// onView(withId(R.id.sPointsToClick)).perform(click());
// onView(withId(R.id.sPointsToClick)).check(ViewAssertions.matches(withListSize(1)));
// Test again to check if the default values remain
mi.click();
// onView(withId(R.id.sPointsToClick)).check(ViewAssertions.matches(withListSize(1)));
} catch ( UiObjectNotFoundException uonfe ){
uonfe.printStackTrace();
fail( uonfe.getMessage() );
}
}
/**
* Inner method to get a dedicated notification and test if this notification is clicakble and display the good activity on click
* @param textContent - The text to use to get the notification
*/
private void testNotificationClick( String textContent ){
UiObject n = null;
if ( Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT_WATCH ){
n = mDevice.findObject(
new UiSelector()
.resourceId("android:id/text")
.className("android.widget.TextView")
.packageName("pylapp.smoothclicker.android")
.textContains(textContent));
} else {
n = mDevice.findObject(
new UiSelector()
.resourceId("android:id/text")
.className("android.widget.TextView")
.packageName("com.android.systemui")
.textContains(textContent));
}
mDevice.openNotification();
n.waitForExists(2000);
try {
n.click();
w(5000);
assertEquals(ClickerActivity.class.getSimpleName(), getActivityInstance().getClass().getSimpleName());
} catch ( UiObjectNotFoundException uonfe ){
uonfe.printStackTrace();
fail();
}
}
@Override
public void action() {
Log.d("ClickUiObjectWatcher triggered!");
if (target != null) {
try {
UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()).findObject(target).click();
} catch (UiObjectNotFoundException e) {
Log.d(e.getMessage());
}
}
}
/**
* Sets the text in an editable field, after clearing the field's content. The UiSelector selector of this object must reference a UI element that is editable. When you call this method, the method first simulates a click() on editable field to set focus. The method then clears the field's contents and injects your specified text into the field. If you want to capture the original contents of the field, call getText() first. You can then modify the text and use this method to update the field.
*
* @param obj the selector of the UiObject.
* @param text string to set
* @return true if operation is successful
* @throws UiObjectNotFoundException
*/
@Override
public boolean setText(Selector obj, String text) throws UiObjectNotFoundException {
try{
obj.toUiObject2().click();
obj.toUiObject2().setText(text);
return true;
}catch(NullPointerException e){
return device.findObject(obj.toUiSelector()).setText(text);
}
}
/**
* Performs a click at the center of the visible bounds of the UI element represented by this UiObject.
*
* @param obj the target ui object.
* @return true id successful else false
* @throws UiObjectNotFoundException
*/
@Override
public boolean click(Selector obj) throws UiObjectNotFoundException {
if (obj.toUiObject2() == null) {
return device.findObject(obj.toUiSelector()).click();
} else {
obj.toUiObject2().click();
return true;
}
}
private boolean click(UiObject obj, String corner) throws UiObjectNotFoundException {
if (corner == null) corner = "center";
corner = corner.toLowerCase();
if ("br".equals(corner) || "bottomright".equals(corner)) return obj.clickBottomRight();
else if ("tl".equals(corner) || "topleft".equals(corner)) return obj.clickTopLeft();
else if ("c".equals(corner) || "center".equals(corner)) return obj.click();
return false;
}