I have an app that uses a UPnP server. For the instrumentation test I want to mock it, i.e. to create my own UPnP server that will be instrumented by the test. Unfortunately it seems the UPnP server cannot run in the same process (in the test package) as the application(which is a UPnP client), so I decided to put this UPnP server in a different APK and control it using Android's Messenger functionality.
I have already setup such IPC for another project so I used some code from there and I am able to successfully send messages from the test (the client) to the UPnP server. However the test cannot receive any message from the server. I send the client's Messenger object in the replyTo field of a message, and the server is using this Messenger to send back another message - the sending seems successful, but nothing arrives at the client. If the client gets disconnected before the server has started sending the reply, then I get an exception during the sending of the reply that the receiver is not available. To me this means that the Messenger object used for the reply is correct.
Has anyone faced some similar issue or knows what is the problem here? Why this Android IPC does not work with instrumentation(functional test)? Is there some difference in Android's handling of the code under a test package?
I assume it doesn't matter, but I am using Robotium for the tests.
So the problem turned out to be (of course) my message Handler.
It was created during the setUp()
of the test, so it is created on a Instrumentation Thread. The execution of test methods is done again in this Instrumentation Thread (unless you annotate it to run on UI thread). This means that while a test method executes, the message Handler cannot be executed, so a message is never received.
Creating the Handler in a new Thread (using a looper), fixed my issue.
This video was very helpful in providing more information about how IPC works in Android, and as well what Messenger really does for you. https://newcircle.com/s/post/1340/deep_dive_into_android_ipc_binder_framework_at_andevcon_iv