Так через некоторое время я хочу опубликовать решение, которое я использую почти всегда. Изначально мне понравилась @ решение 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())
+1 для удивительном Roboelectric :) – fernandohur