如何测试Android绑定服务的客户端绑定到服务的过程?

How to test the process that a client of an Android bound service bind to the service?

我有一个定义绑定服务的服务应用程序,以及另一个客户端应用程序,它的 activity 之一绑定到绑定服务。如何编写测试用例来测试绑定服务进程?

客户端应用程序绑定到服务的代码与Android official doc类似:

public class BindingActivity extends Activity {
    LocalService mService;
    boolean mBound = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    protected void onStart() {
        super.onStart();
        // Bind to LocalService
        Intent intent = new Intent();
        intent.setComponent(new ComponentName(SERVICE_APP_PACKAGE_NAME, 
 SERVICE_NAME));
        bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unbindService(connection);
        mBound = false;
    }

    /** Called when a button is clicked (the button in the layout file attaches to
      * this method with the android:onClick attribute) */
    public void onButtonClick(View v) {
        if (mBound) {
            // Call a method from the LocalService.
            // However, if this call were something that might hang, then this request should
            // occur in a separate thread to avoid slowing down the activity performance.
            int num = mService.getRandomNumber();
            Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();
        }
    }

    /** Defines callbacks for service binding, passed to bindService() */
    private ServiceConnection connection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className,
                IBinder service) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            LocalBinder binder = (LocalBinder) service;
            mService = binder.getService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };
}

什么样的测试用例可以测试activity的onStart()和onStop()方法中的setIntent()&bindService()或unbindService()方法?

您不想测试 onBind。你知道这行得通,作为 Google 框架的一部分进行了测试。您要测试的是两件事:

1)您的 ServiceConnection 函数正确设置了 mBound 和 mService。

2)你的 onStart 调用 onBind 来绑定它。

执行此操作的最佳方法实际上是重构。这段代码不像它应该的那样可测试。将 mService 和 mBound 引入 ServiceConnection class,并使其成为完整的 class(而不是匿名的 class)。然后您可以使用模拟输入轻松测试 (1)。为了测试 (2),我实际上会子 class Activity,重写 bindService 以将变量设置为 true,并确保在调用 onStart 之后变量设置为 true。