下面列出了android.view.MotionEvent.PointerCoords#android.support.test.uiautomator.UiObject 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testChangeText_sameActivity() {
UiObject skipButton = mDevice.findObject(new UiSelector()
.text("SKIP").className("android.widget.TextView"));
// Simulate a user-click on the OK button, if found.
try {
if (skipButton.exists() && skipButton.isEnabled()) {
skipButton.click();
}
} catch (UiObjectNotFoundException e) {
e.printStackTrace();
}
}
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");
}
}
@Ignore
@Test
public void testUiAutomatorAPI() throws UiObjectNotFoundException, InterruptedException {
UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
UiSelector editTextSelector = new UiSelector().className("android.widget.EditText").text("this is a test").focusable(true);
UiObject editTextWidget = device.findObject(editTextSelector);
editTextWidget.setText("this is new text");
Thread.sleep(2000);
UiSelector buttonSelector = new UiSelector().className("android.widget.Button").text("CLICK ME").clickable(true);
UiObject buttonWidget = device.findObject(buttonSelector);
buttonWidget.click();
Thread.sleep(2000);
}
/**
*
*/
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());
}
}
/**
* Inner method to get a dedicated notification and test it
* @param textContent - The text to use to get the notification
*/
private void testIfNotificationExists( 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);
assertTrue(n.exists());
}
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 handleCrash2() {
UiObject window = sDevice.findObject(new UiSelector().packageName("android")
.textContains("has stopped"));
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);
}
UiHelper.takeScreenshots("[CRASH]");
onCrashDetected(errorText);
postHandler();
return true; // triggered
}
return false; // no trigger
}
public static boolean handleCommonDialog() {
UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
UiObject button = null;
for (String keyword : Config.COMMON_BUTTONS) {
button = device.findObject(new UiSelector().text(keyword).enabled(true));
if (button != null && button.exists()) {
break;
}
}
try {
// sometimes it takes a while for the OK button to become enabled
if (button != null && button.exists()) {
button.waitForExists(5000);
button.click();
Log.i("AppCrawlerAction", "{Click} " + button.getText() + " Button succeeded");
return true; // triggered
}
} catch (UiObjectNotFoundException e) {
Log.w(TAG, "UiObject disappear");
}
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());
}
public static boolean viewExistsContains(UiDevice device, String... textToMatch) throws UiObjectNotFoundException
{
if (textToMatch == null || textToMatch.length < 1)
{
return false;
}
UiObject view;
boolean contains = false;
for (int i = 0; i < textToMatch.length; i++)
{
view = device.findObject(new UiSelector().textContains(textToMatch[i]));
contains = view.exists();
if (contains) return true;
}
return false;
}
private ObjInfo(UiObject obj) throws UiObjectNotFoundException {
this._bounds = Rect.from(obj.getBounds());
this._checkable = obj.isCheckable();
this._checked = obj.isChecked();
this._childCount = obj.getChildCount();
this._clickable = obj.isClickable();
this._contentDescription = obj.getContentDescription();
this._enabled = obj.isEnabled();
this._focusable = obj.isFocusable();
this._focused = obj.isFocused();
this._longClickable = obj.isLongClickable();
this._packageName = obj.getPackageName();
this._scrollable = obj.isScrollable();
this._selected = obj.isSelected();
this._text = obj.getText();
this._visibleBounds = Rect.from(obj.getVisibleBounds());
this._className = obj.getClassName();
}
private void allowPermissionsIfNeeded() {
if (Build.VERSION.SDK_INT >= 23) {
// Initialize UiDevice instance
UiDevice uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
// notice that we typically receive 2-3 permission prompts, hence the loop
while (true) {
UiObject allowPermissions = uiDevice.findObject(new UiSelector().text("Allow"));
if (allowPermissions.exists()) {
try {
allowPermissions.click();
} catch (UiObjectNotFoundException e) {
e.printStackTrace();
Log.e(TAG, "There is no permissions dialog to interact with ");
}
} else {
break;
}
}
}
}
public void skipPermission(JSONArray permissionPatterns, int scanningCount) {
UiDevice mDevice = Elements.getGlobal().getmDevice();
// if permission list is empty, avoid execution
if (permissionPatterns.size() == 0) {
return;
}
// regular check for permission scanning
try {
for (int i = 0; i < scanningCount; i++) {
inner:
for (int j = 0; j < permissionPatterns.size(); j++) {
String text = permissionPatterns.getString(j);
UiObject object = mDevice.findObject(new UiSelector().text(text));
if (object.exists()) {
object.click();
break inner;
}
}
Thread.sleep(3000);
}
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println(e.getCause().toString());
}
}
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) {
}
}
}
}
@Test
public void d() throws UiObjectNotFoundException {
// Initialize UiDevice instance
mDevice = UiDevice.getInstance(getInstrumentation());
// Perform a short press on the HOME button
mDevice.pressHome();
// Bring up the default launcher by searching for
// a UI component that matches the content-description for the launcher button
UiObject allAppsButton = mDevice.findObject(new UiSelector().description("Apps"));
// Perform a click on the button to bring up the launcher
allAppsButton.clickAndWaitForNewWindow();
}
/**
* Clicks a button with the given text. This will try to find the widget exactly as the text is given, and
* will try upper casing the text if it is not found.
*/
public static void clickButton(UiDevice device, String buttonText) throws UiObjectNotFoundException
{
UiObject accept = device.findObject(new UiSelector().text(buttonText));
if (accept.exists())
{
accept.click();
return;
}
accept = device.findObject(new UiSelector().text(buttonText.toUpperCase()));
accept.click();
}
protected void click(String target) {
UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
UiObject button = device.findObject(new UiSelector().text(target));
try {
button.click();
} catch (UiObjectNotFoundException e) {
throw new IllegalStateException(e);
}
}
/**
* 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() );
}
}
/**
* Test if the item about credits in the Settings activity starts the credits activity
*/
@Test
public void credits(){
l(this, "@Test credits");
try {
// Swipe to the bottom of the view to get the credits field
UiObject list = mDevice.findObject(
new UiSelector()
.className("android.widget.ListView")
.packageName(PACKAGE_APP_PATH)
.resourceId("android:id/list")
);
list.swipeUp(100);
list.swipeUp(100);
// Clicks on the credits row
String s = InstrumentationRegistry.getTargetContext().getString(R.string.pref_key_credit_title);
UiObject creditsRow = mDevice.findObject(
new UiSelector()
.className("android.widget.TextView")
.packageName(PACKAGE_APP_PATH)
.resourceId("android:id/title")
.text(s)
);
creditsRow.click();
w(1000);
assertEquals(CreditsActivity.class.getSimpleName(), getActivityInstance().getClass().getSimpleName());
} catch ( UiObjectNotFoundException uonfe ){
fail(uonfe.getMessage());
uonfe.printStackTrace();
}
}
/**
* Opens the settings screen from the menu
*/
private void openSettingsScreenFromMenu(){
try {
// Clicks the three-points-icon
UiObject menu = mDevice.findObject(
new UiSelector()
.className("android.widget.ImageView")
.packageName(PACKAGE_APP_PATH)
//.descriptionContains("Plus d'options") // WARNING FIXME French string used, use instead system R values
.descriptionContains("Autres options") // WARNING FIXME French string used, use instead system R values
);
menu.click();
// Clicks on the settings item
String s = InstrumentationRegistry.getTargetContext().getString(R.string.action_settings);
UiObject itemParams = mDevice.findObject(
new UiSelector()
.className("android.widget.TextView")
.packageName(PACKAGE_APP_PATH)
.resourceId(PACKAGE_APP_PATH + ":id/title")
.text(s)
);
itemParams.click();
w(1000);
} catch ( UiObjectNotFoundException uonfe ){
uonfe.printStackTrace();
fail(uonfe.getMessage());
}
w(1000);
}
/**
* @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());
}
}
/**
* Clicks a button with the given text. This will try to find the widget exactly as the text is given, and
* will try upper casing the text if it is not found.
*/
public static void clickButton(UiDevice device, String buttonText) throws UiObjectNotFoundException
{
UiObject accept = device.findObject(new UiSelector().text(buttonText));
if (accept.exists())
{
accept.click();
return;
}
accept = device.findObject(new UiSelector().text(buttonText.toUpperCase()));
accept.click();
}
/**
* Tests the long clicks on the floating action button for stop in the arc menu
*
* <i>A long click on the button to use to stop the process should display a snackbar with an explain message</i>
*/
@Test
public void longClickOnArcMenuStopItem(){
l(this, "@Test longClickOnArcMenuStopItem");
String expectedString = InstrumentationRegistry.getTargetContext().getString(R.string.info_message_stop);
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/fabStop")
);
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() );
}
}
/**
* 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() );
}
}
/**
* Tests the long clicks on the floating action button for new point in the arc menu
*
* <i>A long click on the button to use to add points to click on should display a snackbar with an explain message</i>
*/
@Test
public void longClickOnArcMenuNewPointItem(){
l(this, "@Test longClickOnArcMenuNewPointItem");
String expectedString = InstrumentationRegistry.getTargetContext().getString(R.string.info_message_new_point);
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/fabSelectPoint")
);
fab.waitForExists(WAIT_FOR_EXISTS_TIMEOUT);
assertTrue(fab.isLongClickable());
fab.swipeUp(100); //fab.longClick() makes clicks sometimes, so swipeUp() 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 if the endless repeat checkbox changes modifies well the repeat field
*
* <i>If the check box for the endless repeat is checked, the repeat field is disabled</i>
* <i>If the check box for the endless repeat is unchecked, the repeat field is enabled</i>
*/
@Test
public void changeRepeatOnCheckboxChanges(){
l(this, "@Test changeRepeatOnCheckboxChanges");
try {
UiObject endlessCheckbox = mDevice.findObject(
new UiSelector().resourceId(PACKAGE_APP_PATH + ":id/scEndlessRepeat")
);
UiObject repeatField = mDevice.findObject(
new UiSelector().resourceId(PACKAGE_APP_PATH + ":id/etRepeat")
);
// Check and uncheck the switch
for ( int i = 1; i <= 2; i++ ) {
endlessCheckbox.click();
if (endlessCheckbox.isChecked()) {
assertFalse(repeatField.isEnabled());
} else {
assertTrue(repeatField.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() );
}
}