I had a hard time setting up OpenCV for JUnit tests on Android using MacOS. On the normal app OpenCV was working without any problems but JUnit Tests did not work.
The error that has been thrown is the following:
java.lang.UnsatisfiedLinkError: no opencv_java4 in java.library.path: [/Users/patrick/Library/Java/Extensions, /Library/Java/Extensions, /Network/Library/Java/Extensions, /System/Library/Java/Extensions, /usr/lib/java, .]
I've read a lot of forums and tutorials but they all were either out-dated or not working for me. E.g. adapting the homebrew formula for Java installation, using instrumented tests or directly building the Java sources.
I would now like to share an updated way to setup OpenCV v4.8.0 for JUnit Tests working on Android.
Here is what I did to make it work:
cmake -DCMAKE_SYSTEM_PROCESSOR=arm64 \
--DCMAKE_OSX_ARCHITECTURES=arm64 \
-DWITH_OPENJPEG=OFF \
-DWITH_IPP=OFF \
-D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local/opencv \
-D JAVA_INCLUDE_PATH=$JAVA_HOME/include \
-D JAVA_AWT_LIBRARY=$JAVA_HOME/jre/lib/amd64/libawt.so \
-D JAVA_JVM_LIBRARY=$JAVA_HOME/jre/lib/arm/server/libjvm.so \
-D BUILD_opencv_python2=OFF \
-D BUILD_opencv_java=ON \
-D INSTALL_PYTHON_EXAMPLES=OFF \
-D INSTALL_C_EXAMPLES=OFF \
-D OPENCV_ENABLE_NONFREE=OFF \
-D BUILD_EXAMPLES=ON ..
Now you should see the library: lib/libopencv_java480.dylib
I found that setting
System.setProperty("java.library.path", "/.../opencv-4.8.0/build/lib/libopencv_java480.dylib")
in the JUnit test did not work for me. Therefore I just copied the .dylib
into a directory that is being looked at by the JUnit test:
sudo cp lib/libopencv_java480.dylib /Library/Java/Extensions/libopencv_java480.dylib
Finally, this is the JUnit test (in Kotlin) that worked:
class UnitTest {
@BeforeEach
fun setUp() {
System.loadLibrary( "opencv_java480" )
// do some OpenCV stuff
}
}
In the build.gradle
file I've added the following (on root level):
tasks.withType(Test) {
useJUnitPlatform()
}