How to unit test serial ports in Java on Android

2019-09-05 03:12发布

问题:

I'm aware that Android does not provide out-of-the-box access to the serial ports unless the device is rooted or a custom Android version is flashed, say on a BeagleBone Black board -- which is exactly my case. Using the Android SerialPort API project I am able to access and test the serial ports of my device through the sample GUI app (slightly modified).

However, I'd like to also add JUnit tests for the Serial API because I will be expanding it into a library module for client programmers to use. I tried using AndroidTestCase, but I'm receiving the error:

java.lang.UnsatisfiedLinkError: Native method not found:  
com.XXX.android.serialport_api.SerialPort.open:  
(Ljava/lang/String;II)Ljava/io/FileDescriptor;
at com.XXX.android.serialport_api.SerialPort.open(Native 
Method)
at com.XXX.android.serialport_api.SerialPort.<init    
(SerialPort.java:32)

It seems to me the serialport.so files are not loaded/visible inside the mock environment provided by AndroidTestCase. I'm using the standard test structure created by the "New Module" wizard in Android Studio.

Any advice or hint would be appreciated because my search on the topic turned nothing out. I'll be happy to provide test class and implementation if needed (although the implementation is pretty much the same as the SerialPort.java class in the open source sample referenced above).

回答1:

I found the issue. The package name is hardcoded in the pre-compiled .so files. So instead of using a custom package name like com.XXX.XXX one has to put the SerialPort (and other implementing classes) in a top-level package directly under the /java folder. The package name should be exactly android_serialport_api -- just like in the library sample.