Handler.handleMessage在测试中未调用,但在应用程序中调用

bmv*_*143 3 java android android-service android-testing android-handler

我有一个在单独进程中运行的服务.该服务在onCreate()方法中生成一个新线程.该线程将消息发送回服务.

如果我手动启动应用程序一切正常 - Handler我的服务收到消息.但在我的测试handleMessage()方法中永远不会被调用.

如何修复测试以使handleMessage()方法有效?

谢谢!

服务:

public class MyService extends Service {

    private ServiceHandler mHandler;
    private final int MSG_HELLO_WORLD = 1;

    private final String TAG = getClass().getSimpleName();

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return null;
    }


    @Override
    public void onCreate() {
        Log.d(TAG, "MyService.onCreate");
        super.onCreate();

        mHandler = new ServiceHandler();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "Thread: run()");

                while (true) {

                    try {
                        Log.d(TAG, "sleeping...");
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        Log.d(TAG, "Thread was interrupted.");
                        break;
                    }

                    Log.d(TAG, "sending message...");
                    Message msg = Message.obtain(mHandler, MSG_HELLO_WORLD);
                    msg.sendToTarget();
                }
            }
        }).start();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "MyService.onStartCommand");
        return START_REDELIVER_INTENT;
    }

    private class ServiceHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            Log.d(TAG, "ServiceHandler.handleMessage");

            if (msg.what == MSG_HELLO_WORLD) {
                Log.d(TAG, "Hello World message received!");
            }
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

测试:

public class MyServiceTest extends ServiceTestCase<MyService> {

    private static final String TAG = MyService.class.getSimpleName();

    public MyServiceTest() {
        super(MyService.class);
    }


    public void setUp() throws Exception {
        super.setUp();
    }


    public void testStartService() throws Exception {

        Intent startServiceIntent = new Intent(getContext(), MyService.class);

        startService(startServiceIntent);

        MyService myService = getService();

        assertNotNull(myService);

        // give the service some time to send messages
        Thread.sleep(10000);
    }
}
Run Code Online (Sandbox Code Playgroud)

App的logcat输出(handleMessage()被调用):

MyService.onCreate
MyService.onStartCommand
Thread: run()
sleeping...
sending message...
sleeping...
ServiceHandler.handleMessage
Hello World message received!
sending message...
sleeping...
Run Code Online (Sandbox Code Playgroud)

测试的logcat输出(handleMessage()未调用):

MyService.onCreate
MyService.onStartCommand
Thread: run()
sleeping...
sending message...
sleeping...
sending message...
sleeping...
sending message...
sleeping...
Run Code Online (Sandbox Code Playgroud)

Oni*_*nik 6

你的问题对我很有意思,所以我开始挖掘.

如果我手动启动应用程序一切正常 - Handler我的服务收到消息.

mHandler在使用MyServiceonCreate()方法中初始化时mHandler = new ServiceHandler(),Handler它与当前执行的线程的消息队列相关联.mHandler过程Messages从在其又由处理的队列Looper,其是循环.结果您可以看到"收到Hello World消息!" 在日志中.

但在我的测试handleMessage()方法中永远不会被调用.

当您测试服务时,调用其方法InstrumentationThread(请参阅其中的线程Debugger),这些方法Looper准备好但未循环,因此无法处理消息并且不会在日志中显示消息.

如何修复我的测试以使handleMessage()方法有效?

我建议以下选项:

  • 绑定MyServiceTestMyService调用方法的线程.unit test为组件再写一次,然后将测试与MyServiceTest一个公共.java测试文件结合起来.这将显示所需的logcat输出.
  • 河套准备LooperInstrumentationThreadMyServiceTest.你可以通过添加Looper.loop()以下testStartService()方法来实现MyServiceTest:

    public void testStartService() throws Exception {
    
        Intent startServiceIntent = new Intent(getContext(), MyService.class);
        startService(startServiceIntent);
        MyService myService = getService();
        assertNotNull(myService);
    
        // Run the Looper (this call is to be added)
        Looper.loop();
    
        Thread.sleep(10000);
    }
    
    Run Code Online (Sandbox Code Playgroud)

    注意:运行Looper将显示所需的logcat输出,但测试不会因为Looper.loop()无限期运行而停止,直到您调用Looper.quit().