Unit test Java class that loads native library

前端 未结 8 610
自闭症患者
自闭症患者 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:34

    If the library is required for your test, use an AndroidTest (under src/androidTest/...) rather than a junit test. This will allow you to load and use the native library like you do elsewhere in your code.

    If the library is not required for your test, simply wrap the system load in a try/catch. This will allow the JNI class to still work in junit tests (under src/test/...) and it is a safe workaround, given that it is unlikely to mask the error (something else will certainly fail, if the native lib is actually needed). From there, you can use something like mockito to stub out any method calls that still hit the JNI library.

    For example in Kotlin:

        companion object {
            init {
                try {
                    System.loadLibrary("mylibrary")
                } catch (e: UnsatisfiedLinkError) {
                    // log the error or track it in analytics
                }
            }
        }
    

提交回复
热议问题