下面列出了怎么用android.support.test.uiautomator.UiSelector的API类实例代码及写法,或者点击链接到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);
}
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;
}
/**
* 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());
}
/**
* Inner method to get a dedicated notification and test it
* @param textContent - The text to use to get the notification
*/
private void testNotification( 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(60000);
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 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 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 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());
}
/**
* Register a ClickUiObjectWatcher
*
* @param name Watcher name
* @param conditions If all UiObject in the conditions match, the watcher should be triggered.
* @param target The target UiObject should be clicked if all conditions match.
*/
@Override
public void registerClickUiObjectWatcher(String name, Selector[] conditions, Selector target) {
synchronized (watchers) {
if (watchers.contains(name)) {
device.removeWatcher(name);
watchers.remove(name);
}
UiSelector[] selectors = new UiSelector[conditions.length];
for (int i = 0; i < conditions.length; i++) {
selectors[i] = conditions[i].toUiSelector();
}
device.registerWatcher(name, new ClickUiObjectWatcher(selectors, target.toUiSelector()));
watchers.add(name);
}
}
/**
* Register a PressKeysWatcher
*
* @param name Watcher name
* @param conditions If all UiObject in the conditions match, the watcher should be triggered.
* @param keys All keys will be pressed in sequence.
*/
@Override
public void registerPressKeyskWatcher(String name, Selector[] conditions, String[] keys) {
synchronized (watchers) {
if (watchers.contains(name)) {
device.removeWatcher(name);
watchers.remove(name);
}
UiSelector[] selectors = new UiSelector[conditions.length];
for (int i = 0; i < conditions.length; i++) {
selectors[i] = conditions[i].toUiSelector();
}
device.registerWatcher(name, new PressKeysWatcher(selectors, keys));
watchers.add(name);
}
}
/**
* Get the count of the UiObject instances by the selector
*
* @param obj the selector of the ui object
* @return the count of instances.
*/
@Override
public int count(Selector obj) {
if ((obj.getMask() & Selector.MASK_INSTANCE) > 0) {
if (device.findObject(obj.toUiSelector()).exists()) return 1;
else return 0;
} else {
UiSelector sel = obj.toUiSelector();
if (!device.findObject(sel).exists()) return 0;
int low = 1;
int high = 2;
sel = sel.instance(high - 1);
while (device.findObject(sel).exists()) {
low = high;
high = high * 2;
sel = sel.instance(high - 1);
}
while (high > low + 1) {
int mid = (low + high) / 2;
sel = sel.instance(mid - 1);
if (device.findObject(sel).exists()) low = mid;
else high = mid;
}
return low;
}
}
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 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;
}
@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"));
}
@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"));
}
@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"));
}
@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 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();
}
protected void click(String targetId) {
UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
UiObject button = device.findObject(new UiSelector().resourceId(targetId));
try {
button.waitForExists(3000);
button.click();
} catch (UiObjectNotFoundException e) {
throw new IllegalStateException(e);
}
}
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() );
}
}