Espresso How to access views without using R.id.vi

2019-05-31 01:29发布

问题:

I am switching from robotium to espresso, I am writing tests using apk, I dont have access to code. In robotium using solo.getView("view-id") we can access the view but I am not geting how to do it in espresso? espresso witId() method needs R.id.viewid which I dont have access.

public class AaEspressoTest {

private static final String LAUNCHER_ACTIVITY_FULL_CLASSNAME = "com.tri.re.CordActivity";
private static Class<?> launcherActivityClass;

static {
    try {
        launcherActivityClass = Class.forName(LAUNCHER_ACTIVITY_FULL_CLASSNAME);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}

@Rule
public ActivityTestRule<?> mActivityRule = new ActivityTestRule(launcherActivityClass);


@Test public void testHello() throws Exception{

    onView(withText("Browse older recordings")).perform(click());

   //Id is not accessible shows red
    onView(withId(R.id.button)).perform(click());

}

}

回答1:

You can use a helper function to get the id:

private static int getId(String id) {
  Context targetContext = InstrumentationRegistry.getTargetContext();
  String packageName = targetContext.getPackageName();
  return targetContext.getResources().getIdentifier(id, "id", packageName);
}

Then you can use the id in Espresso:

onView(withId(getId("button"))).perform(click());


回答2:

You can use the uiautomator from command line or by opening the Android Device Monitor's Hierarchy Viewer to dump the current visible screen of the app and get a lot of information from each of the screen views, including the resource id, which is the view id you will want to use on your test.

Genynmotion doesn't show the id's for some reason, but with a real device or Android's emulator it should work.