在我的应用程序中,当用户单击“注册”按钮时,将启动RegisterActivity.用户填写表单后,详细信息将发布到Web服务,如果注册成功,则RegisterActivity将使用RESULT_OK进行填充.这在以下代码示例中进行了总结:
public void submitRegistration() { showProgressDialog(R.string.registration,R.string.please_wait); getWebApi().register(buildRegistrationFromUI(),new Callback<ApiResponse>() { @Override public void success(ApiResponse apiResponse,Response response) { hideProgressDialog(); setResult(RESULT_OK); finish(); } @Override public void failure(RetrofitError error) { hideProgressDialog(); showErrorDialog(ApiError.parse(error)); } }); }
使用Espresso,如何使用setResult(RESULT_OK)检查活动是否已完成.
请注意:我不想创建模拟意图,我想检查意图结果状态.
解决方法
所有setResult(…)方法都是更改Activity类中字段的值
public final void setResult(int resultCode,Intent data) { synchronized (this) { mResultCode = resultCode; mResultData = data; } }
因此,我们可以使用Java Reflection访问mResultCode字段以测试该值是否确实已设置为RESULT_OK.
@Rule public ActivityTestRule<ContactsActivity> mActivityRule = new ActivityTestRule<>( ContactsActivity.class); @Test public void testResultOk() throws NoSuchFieldException,IllegalAccessException { Field f = Activity.class.getDeclaredField("mResultCode"); //NoSuchFieldException f.setAccessible(true); int mResultCode = f.getInt(mActivityRule.getActivity()); assertTrue("The result code is not ok. ",mResultCode == Activity.RESULT_OK); }