这是我从 MainActivity 创建的测试。
@RunWith(AndroidJUnit4.class)
public class MainActivityTest {
public static final String KEY_IMAGE_DATA = "data";
MainActivity mainActivity;
@Rule
public ActivityTestRule<MainActivity> mainActivityRule =
new ActivityTestRule(MainActivity.class,true,false);
我正在使用 IntensTestRule 从相机获取结果,这在 MainActivity 的其他地方是必要的。
@Rule
public IntentsTestRule<MainActivity> mIntentsTestRule =
new IntentsTestRule<>(MainActivity.class);
@Before
public void grantPhonePermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
getInstrumentation().getUiAutomation().executeShellCommand(
"pm grant " + getTargetContext().getPackageName()
+ " android.permission.CAMERA");
getInstrumentation().getUiAutomation().executeShellCommand(
"pm grant " + getTargetContext().getPackageName()
+ " android.permission.WRITE_EXTERNAL_STORAGE");
getInstrumentation().getUiAutomation().executeShellCommand(
"pm grant " + getTargetContext().getPackageName()
+ " android.permission.READ_EXTERNAL_STORAGE");
}
}
@Before
public void StubCameraIntent() {
Instrumentation.ActivityResult result = createImageCaptureStub();
intending(hasAction(MediaStore.ACTION_IMAGE_CAPTURE)).respondWith(result);
}
在这里,我尝试使用我从上一个活动中提出的一些参数来启动 MainActivity。
@Test
public void testFormOnMainActivity() {
Context targetContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
Intent intentOpenWindow = new Intent(targetContext, MainActivity.class);
intentOpenWindow.putExtra("id","1");
intentOpenWindow.putExtra("email","xyz@hotmail.com");
intentOpenWindow.putExtra("name", "xyz");
...
Bundle b = new Bundle();
b.putParcelable("Coordinate", coords);
intentOpenWindow.putExtra("bundle", b);
...
grantPhonePermission();
mainActivityRule.launchActivity(intentOpenWindow);
onView(withId(R.id.btnGetDni)).perform(click());
intended(toPackage("com.android.camera"));
}
private Instrumentation.ActivityResult createImageCaptureStub() {
Bundle bundle = new Bundle();
bundle.putParcelable(KEY_IMAGE_DATA,
BitmapFactory.decodeResource(mIntentsTestRule.getActivity().getResources(), R.drawable.camera_24));
Intent resultData = new Intent();
resultData.putExtras(bundle);
return new Instrumentation.ActivityResult(Activity.RESULT_OK, resultData);
}
}
这是 Main Activity ,它总是收到一个空 Intent。
public class MainActivity extends AppCompatActivity {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
Bundle bundle = getIntent().getExtras();
idFacebook = bundle.getString("id");
String email = bundle.getString("email");
String name = bundle.getString("name");
logUser(idFacebook,email,name);
bundle.setClassLoader(Coords.class.getClassLoader());
timeStapLoginFacebook = bundle.getLong("TimeStapLoginFacebook");
gpsStatus = bundle.getBoolean("GPS");
Bundle bundllle = getIntent().getBundleExtra("bundle");
coordsFacebook = bundllle.getParcelable("Coordinate");
...
}
...
}