Unit test Java class that loads native library

前端 未结 8 612
自闭症患者
自闭症患者 2021-02-01 11:49

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(\"myli         


        
8条回答
  •  走了就别回头了
    2021-02-01 12:51

    I am not sure whether this solves your problem or not but so far nobody has mentioned about strategy pattern for dealing with classes preloading library during their creation.

    Let's see the example:

    We want to implement Fibonacci solver class. Assuming that we provided implementation in the native code and managed to generate the native library, we can implement the following:

    public interface Fibonacci {
         long calculate(int steps);
    }
    

    Firstly, we provide our native implementation:

    public final class FibonacciNative implements Fibonacci {
        static {
          System.loadLibrary("myfibonacci");
        }
    
        public native long calculate(int steps);
    }
    

    Secondly, we provide Java implementation for Fibonacci solver:

    public final class FibonacciJava implements Fibonacci {
    
       @Override
       public long calculate(int steps) {
           if(steps > 1) {
               return calculate(steps-2) + calculate(steps-1);
           }
           return steps;
       }
    }
    

    Thirdly, we wrap the solvers with parental class choosing its own implementation during its instantiation:

    public class FibonnaciSolver implements Fibonacci {
    
       private static final Fibonacci STRATEGY;
    
       static {
          Fibonacci implementation;
          try {
             implementation = new FibonnaciNative();
          } catch(Throwable e) {
             implementation = new FibonnaciJava();
          }
    
          STRATEGY = implementation;
       }
    
       @Override
       public long calculate(int steps) {
           return STRATEGY.calculate(steps);
       }
    
    }
    

    Thus, the problem with finding path to the library using strategy. This case, however, does not resolve the problem if the native library is really necessary to be included during the test. It does not neither solve the problem if the native library is a third-party library.

    Basically, this gets around the native library load problem by mocking out the native code for java code.

    Hope this helps somehow:)

提交回复
热议问题