uve*_*ten 16 java junit android unit-testing android-intent
我目前正在编写一些Android单元测试,虽然我已经按照我想要的方式完成了大部分工作,但有一件事让我有点难过.
我在测试的活动中有以下代码:
Intent result = new Intent();
result.putExtra("test", testinput.getText().toString());
setResult(Activity.RESULT_OK, result);
finish();
Run Code Online (Sandbox Code Playgroud)
我试图弄清楚如何使用Instrumentation(或其他)来读取活动的结果,或者在活动结束后获得意图.有人可以帮忙吗?
Val*_*s R 21
您可以使用反射并直接从Activity中获取值.
protected Intent assertFinishCalledWithResult(int resultCode) {
assertThat(isFinishCalled(), is(true));
try {
Field f = Activity.class.getDeclaredField("mResultCode");
f.setAccessible(true);
int actualResultCode = (Integer)f.get(getActivity());
assertThat(actualResultCode, is(resultCode));
f = Activity.class.getDeclaredField("mResultData");
f.setAccessible(true);
return (Intent)f.get(getActivity());
} catch (NoSuchFieldException e) {
throw new RuntimeException("Looks like the Android Activity class has changed it's private fields for mResultCode or mResultData. Time to update the reflection code.", e);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Run Code Online (Sandbox Code Playgroud)
Edu*_*ora 10
或者您也可以使用Robolectric并对正在测试的Activity进行阴影处理.然后,ShadowActivity为您提供了方法,可以轻松了解活动是否正在完成以及检索其结果代码.
举个例子,我的一个测试看起来像这样:
@Test
public void testPressingFinishButtonFinishesActivity() {
mActivity.onCreate(null);
ShadowActivity shadowActivity = Robolectric.shadowOf(mActivity);
Button finishButton = (Button) mActivity.findViewById(R.id.finish_button);
finishButton.performClick();
assertEquals(DummyActivity.RESULT_CUSTOM, shadowActivity.getResultCode());
assertTrue(shadowActivity.isFinishing());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14341 次 |
| 最近记录: |