0

I would like to test an activity from an other apk, and this test extends ActivityInstrumentationTestCase2 (http://developer.android.com/reference/android/test/ActivityInstrumentationTestCase2.html) because I will need to get the Activity and Instrumentation.

I try to use a DexClassLoader like this:

    public MainActivityTest() throws ClassNotFoundException{
    super((new DexClassLoader(
                "/data/app/my-application.apk", "/data/app/my-application",null, MainActivityTest.class.getClassLoader())).loadClass("my-application.MainActivity")))}

But I get as result an Exception: optimizedDirectory not readable/writable: /data/data/valentin.myapplication2

Is there a solution to do it?

I need the activity because i use this after: activity.getWindow().getDecorView()

FYI:

@Before
public void setUp() throws Exception {
    super.setUp();
    injectInstrumentation(InstrumentationRegistry.getInstrumentation());
    mActivity = getActivity();
}

@Test
public void testRecorder(){

   new ActivityListener(InstrumentationRegistry.getInstrumentation(),mActivity,12).start();
    while(true){
    }
}
vmagrez
  • 69
  • 2
  • 11
  • Maybe you could use Espresso. [Look here](https://github.com/googlesamples/android-testing/blob/master/ui/espresso/BasicSample/app/src/androidTest/java/com/example/android/testing/espresso/BasicSample/ChangeTextBehaviorTest.java) there is an example. which already features an test with an acitivty. Hope this helps you. Otherwise I would say the path looks suspicious to me. – Templum Feb 10 '16 at 16:38

1 Answers1

0

You should never hardcode paths like that in your code. First off, /data/app is the wrong path - that is where the apk itself lives and only the system can write there. You can use getFilesDir() to get the path to your applications data directory, which you can write to.

When using DexClassLoader, you have to provide a path that is writable, because the system will optimize the dex file and write the optimized version to the location you specify.

public Class getActivityClass(Context ctx)
        throws PackageManager.NameNotFoundException, ClassNotFoundException {
    ApplicationInfo pi = ctx.getPackageManager()
    .getApplicationInfo("my.application", 0);
    String apkPath = pi.sourceDir;

    DexClassLoader loader = new DexClassLoader(apkPath,
            ctx.getFilesDir().getAbsolutePath(), null,
            this.getClass().getClassLoader());
    return loader.loadClass("my-application.MainActivity");
}
JesusFreke
  • 19,784
  • 5
  • 65
  • 68