经过一段时间后,我想发布我几乎总是使用的解决方案。最初我喜欢@aleph_null的解决方案,但事实证明它使测试变得难以忍受,所以现在我使用的是:
首先,我有这个接口
public interface ActivityLauncher {
public void start(Context context, Intent intent);
public Intent getIntent();
}
而我有两种实现方式:
public class DefaultActivityLauncher implements ActivityLauncher{
private Intent intent;
public DefaultActivityLauncher(){}
@Override
public void start(Context context, Intent intent) {
this.intent = intent;
context.startActivity(intent);
}
@Override
public Intent getIntent() {
return intent;
}
}
并且
public class MockActivityLauncher implements ActivityLauncher {
private Intent intent;
@Override
public void start(Context context, Intent intent) {
this.intent = intent;
}
@Override
public Intent getIntent() {
return intent;
}
}
然后我使用类似于
Dagger
的依赖注入框架,就像这样:
public class MyActivity {
@Inject ActivityLauncher launcher;
public void onCreate(Bundle bundle){
findViewById(R.id.goToOtherActivityButton).setOnClick(new OnClickListener(){
Intent intent = new Intent(getContext(), MyOtherActivity.class);
launcher.start(getContext(), intent);
});
}
public ActivityLauncher getLauncher(){
return launcher;
}
}
测试就像这样简单:checkIntentIsValid(activity.geLauncher().getIntent())