Android JUnit Testing for Native Libraries

Recently, when writing Unit Test at work, I encountered the problem that OpenCV Method could not be used when running Unit Test.

Later, I found out that it was because I couldn't dynamically load the Native Library, which is the C Library, when doing the Unit Test.

Here are three possible approaches to consider:

  1. Avoid all unit test sections that would call the native function directly, don't test the native function, or change the native function to a mock method to do some return results, and test directly.
  2. If the test also needs to use the native function, then you must dynamically load the c library at the unit test build time. This seems a bit difficult, you need to write some code, and you also need to move all the related files required by the open cv library to the module. You can refer to some articles:

    Unit Test Your NDK Library Integration

    Android JUnit and Native Libraries

  3. Test the unit test directly on the emulator or hardware, and rely on hardware to load the c lib. In this way, you can test directly, and the changes are relatively small. In reality, I imagine that a debug page should be written, where the unit test can be run, and executed when clicked.

Click here to share this article with your friends on X if you liked it.