Robolectric tanks on Application objects that load JNI libraries. Can I get a workaround?

大城市里の小女人 提交于 2019-11-30 13:49:05
Christopher Perry

Solution works for Robolectric 1.2, not 2.+

Thanks to Jan Berkel for answering this here: https://groups.google.com/d/msg/robolectric/beW9XjT8E1A/pJQrRaybN30J

class MyJniClass {
 static {
        try {
            System.loadLibrary("libname");
        } catch (UnsatisfiedLinkError e) {
            // only ignore exception in non-android env
            if ("Dalvik".equals(System.getProperty("java.vm.name"))) throw e;
        }
    }
}

then in the testrunner:

public class MyTestRunner  extends RobolectricTestRunner {
   public MyTestRunner(Class testClass) throws InitializationError {
         // remove native calls + replace with shadows
        addClassOrPackageToInstrument("com.example.jni.MyJniClass");
   }

   protected void bindShadowClasses() {
         // bind shadow JNI classes
   }
}

One option for apps with heavyweight Application classes that don't work well with Robolectric is to create an empty Application object and use this for your Robolectric tests:

Something like this:

public void EmptyApp extends Application { 
}

Then your test setup can look like this:

@RunWith(RobolectricTestRunner.class)
@Config(application = EmptyApplication.class, manifest = "src/main/AndroidManifest.xml", sdk = 23)   

Since you have referenced the manifest, all of the resources will still be available in Context#getString(int id) and so on.

As @Jared pointed out, the solution @Christopher gave doesn't work for Robolectric 2 or 3.

The solution I ended up using was to add the environmental variable:

ROBOLECTRIC=TRUE

to the build configuration for my tests. (Run -> Edit Configurations, Environmental Variables).

Then you check for that environmental variable before loading problematic libraries. For example:

class MyClass {
    if(System.getenv("ROBOLECTRIC") == null) {
        System.loadLibrary("libname");
    }
}

Obviously you won't be able to test any code that relies on that library, but at least some testing will be possibel!

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