【问题标题】:How to test the process that a client of an Android bound service bind to the service?如何测试Android绑定服务的客户端绑定到服务的过程?
【发布时间】:2021-10-12 17:54:29
【问题描述】:

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

客户端App绑定服务的代码与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()方法?

【问题讨论】:

    标签: android bindservice


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-24
      • 2012-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      • 1970-01-01
      相关资源
      最近更新 更多