0

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

客户端App绑定服务的代码与Android官方文档类似:

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()方法?

4

1 回答 1

0

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

1)您的ServiceConnection 功能正确设置了mBound 和mService。

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

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

于 2021-10-12T20:24:14.127 回答