Unit test Java class that loads native library

ThanosFisherman picture ThanosFisherman · Jan 15, 2016 · Viewed 15.6k times · Source

I'm running unit tests in Android Studio. I have a Java class that loads a native library with the following code

 static
    {
       System.loadLibrary("mylibrary");
    }

But when I test this class inside my src/test directory I get

java.lang.UnsatisfiedLinkError: no mylibrary in java.library.path
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1864)
    at java.lang.Runtime.loadLibrary0(Runtime.java:870)
    at java.lang.System.loadLibrary(System.java:1122)

How can I make it find the path of native .so libraries which is located at src/main/libs in order to unit test without errors?

Note: inside src/main/libs directory I have 3 more subdirectories: armeabi, mips and x86. Each one of those contains the proper .so file. I'm using the Non experimental version for building NDK libs.

I don't wanna use other 3rd party testing libraries as all my other "pure" java classes can be unit tested fine. But if that's not possible then I'm open to alternatives.

Here is my test code which throws the error

   @Test
    public void testNativeClass() throws Exception
    {
        MyNativeJavaClass test = new MyNativeJavaClass("lalalal")
        List<String> results = test.getResultsFromNativeMethodAndPutThemInArrayList();
        assertEquals("There should be only three result", 3, results.size());
    }

Answer

ThanosFisherman picture ThanosFisherman · Feb 4, 2016

The only solution I found that works without hacks is to use JUnit through instrumentation testing (androidTest directory). My class can now be tested fine but with help of the android device or emulator.