Espresso How to access views without using R.id.viewid as we do in robotium?

放肆的年华 提交于 2019-12-08 05:04:37

问题


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.



来源:https://stackoverflow.com/questions/29946970/espresso-how-to-access-views-without-using-r-id-viewid-as-we-do-in-robotium

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!