1 package com.xtremelabs.robolectric.matchers; 2 3 import android.app.Activity; 4 import android.content.Context; 5 import android.content.ContextWrapper; 6 import android.content.Intent; 7 import com.xtremelabs.robolectric.shadows.ShadowIntent; 8 import org.hamcrest.Description; 9 import org.junit.internal.matchers.TypeSafeMatcher; 10 11 import static com.xtremelabs.robolectric.Robolectric.shadowOf; 12 13 public class StartedMatcher extends TypeSafeMatcher<Context> { 14 private final Intent expectedIntent; 15 16 private String message; 17 18 public StartedMatcher(Intent expectedIntent) { 19 this.expectedIntent = expectedIntent; 20 } 21 22 public StartedMatcher(String packageName, Class<? extends Activity> expectedActivityClass) { 23 this(createIntent(packageName, expectedActivityClass)); 24 } 25 26 public StartedMatcher(Class<? extends Activity> expectedActivityClass) { 27 this(createIntent(expectedActivityClass)); 28 } 29 30 public StartedMatcher(Class<? extends Activity> expectedActivityClass, String expectedAction) { 31 this(createIntent(expectedActivityClass)); 32 33 expectedIntent.setAction(expectedAction); 34 } 35 36 @Override 37 public boolean matchesSafely(Context actualContext) { 38 if (expectedIntent == null) { 39 message = "null intent (did you mean to expect null?)"; 40 return false; 41 } 42 43 String expected = expectedIntent.toString(); 44 message = "to start " + expected + ", but "; 45 46 Intent actualStartedIntent = shadowOf((ContextWrapper) actualContext).getNextStartedActivity(); 47 48 if (actualStartedIntent == null) { 49 message += "didn't start anything"; 50 return false; 51 } 52 53 ShadowIntent shadowIntent = shadowOf(actualStartedIntent); 54 55 boolean intentsMatch = shadowOf(expectedIntent).realIntentEquals(shadowIntent); 56 if (!intentsMatch) { 57 message += "started " + actualStartedIntent; 58 } 59 return intentsMatch; 60 } 61 62 @Override 63 public void describeTo(Description description) { 64 description.appendText(message); 65 } 66 67 public static Intent createIntent(Class<? extends Activity> activityClass, String extraKey, String extraValue) { 68 Intent intent = createIntent(activityClass); 69 intent.putExtra(extraKey, extraValue); 70 return intent; 71 } 72 73 public static Intent createIntent(Class<? extends Activity> activityClass, String action) { 74 Intent intent = createIntent(activityClass); 75 intent.setAction(action); 76 return intent; 77 } 78 79 public static Intent createIntent(Class<? extends Activity> activityClass) { 80 String packageName = activityClass.getPackage().getName(); 81 return createIntent(packageName, activityClass); 82 } 83 84 public static Intent createIntent(String packageName, Class<? extends Activity> activityClass) { 85 Intent intent = new Intent(); 86 intent.setClassName(packageName, activityClass.getName()); 87 return intent; 88 } 89 } 90