我尝试使用UIautomator和Espresso来获取Android Marshmallow和Nougat的位置权限。我有一个简单的测试点击"允许"按钮。当我通过android studio运行它时,它确实有效,但是当我通过命令行运行它时,使用./gradlew connectedCheck,测试不会执行。这是我的代码:
@RunWith(AndroidJUnit4.class)
@SdkSuppress(minSdkVersion = 18)
public class AllowLocation {
@Rule
public ActivityTestRule<MainActivity> activityRule =
new ActivityTestRule<>(MainActivity.class);
public boolean isFirstTime() {
if (activityRule.getActivity() != null) {
return false;
}
return true;
}
public void checkFirstTimeOpen() {
if (isFirstTime()) {
SystemClock.sleep(1000);
onView(allOf(withId(R.id.txt_login_cross), withText("X"), isDisplayed()))
.perform(click());
}
}
@Test
public void allowLocation() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !isFirstTime()) {
checkFirstTimeOpen();
UiDevice mDevice = UiDevice.getInstance(getInstrumentation());
UiObject allowPermissions = mDevice.findObject(new UiSelector().text("Allow"));
if (allowPermissions.exists()) {
try {
allowPermissions.click();
Log.d("Permission clicked", "MainActivity.class");
} catch (UiObjectNotFoundException e) {
Log.d(e.toString(), "There is no permissions dialog to interact with ");
}
}
}
}
}