Created
June 3, 2016 13:44
-
-
Save kingargyle/b36b2340d72dc8dfe3d4fdd8690e5a4d to your computer and use it in GitHub Desktop.
ShadowSupportFragment implementation for Robolectric
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Intent; | |
import android.os.Bundle; | |
import android.support.v4.app.Fragment; | |
import java.util.ArrayList; | |
import java.util.HashMap; | |
import java.util.List; | |
import java.util.Map; | |
import org.robolectric.annotation.Implementation; | |
import org.robolectric.annotation.Implements; | |
import org.robolectric.shadows.ShadowApplication; | |
/** | |
* Based on code from Robolectric ShadowActivity class. | |
* https://github.com/robolectric/robolectric/blob/master/robolectric-shadows/shadows-core/src/main/resources/org/robolectric/shadows/ShadowActivity.java.vm | |
*/ | |
@Implements(Fragment.class) | |
public class ShadowSupportFragment { | |
private List<IntentForResult> startedActivitiesForResults = new ArrayList<>(); | |
private Map<Intent.FilterComparison, Integer> intentRequestCodeMap = new HashMap<>(); | |
@Implementation public void startActivityForResult(Intent intent, int requestCode) { | |
intentRequestCodeMap.put(new Intent.FilterComparison(intent), requestCode); | |
startedActivitiesForResults.add(new IntentForResult(intent, requestCode)); | |
ShadowApplication.getInstance().startActivity(intent); | |
} | |
public IntentForResult getNextStartedActivityForResult() { | |
if (startedActivitiesForResults.isEmpty()) { | |
return null; | |
} else { | |
return startedActivitiesForResults.remove(0); | |
} | |
} | |
public IntentForResult peekNextStartedActivityForResult() { | |
if (startedActivitiesForResults.isEmpty()) { | |
return null; | |
} else { | |
return startedActivitiesForResults.get(0); | |
} | |
} | |
/** | |
* Container object to hold an Intent, together with the requestCode used | |
* in a call to {@code Fragment.startActivityForResult(Intent, int)} | |
*/ | |
public class IntentForResult { | |
public Intent intent; | |
public int requestCode; | |
public Bundle options; | |
public IntentForResult(Intent intent, int requestCode) { | |
this.intent = intent; | |
this.requestCode = requestCode; | |
this.options = null; | |
} | |
public IntentForResult(Intent intent, int requestCode, Bundle options) { | |
this.intent = intent; | |
this.requestCode = requestCode; | |
this.options = options; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment