所以一段时间后,我想发布我几乎总是使用的解决方案。最初我喜欢@aleph_null 的解决方案,但事实证明它使测试慢得难以忍受,所以这就是我现在使用的:
首先,我有这个interface
/**
* Simple interface to launch other activities.
*/
public interface ActivityLauncher {
/**
* Starts an activity with the Intent provided.
* @param intent an intent
*/
public void start(Context context, Intent intent);
/**
*
* Returns the intent as set by {@link #start(android.content.Context, android.content.Intent) start} or null if not yet
* called.
*
* @return an intent or null
*/
public Intent getIntent();
}
我有两个实现:
/**
* Default implementation of ActivityLauncher
*/
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;
}
}
和
/**
* Mock implementation of ActivityLauncher that simply sets the intent but does not actually starts
* an activity.
*/
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){
// some code omitted for brevity
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())