使用Espresso测试Activity和特定的Fragment

5

我的Activity承载了两个碎片(Fragments)。在onCreate()方法中,我会判断哪一个碎片需要被展示。

@Override
protected void onCreate(Bundle savedInstanceState) {
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    handleIntent(getIntent());
}


private void handleIntent(Intent intent) {
    LogUtils.d(TAG, "handleIntent action=" + intent.getAction());
    if (MainIntentService.ACTION_TARGET_OPENER.equals(intent.getAction())) {
        loadOpener();
    } else if (MainIntentService.ACTION_TARGET_LOGIN.equals(intent.getAction())) {
        loadLogin();
    } else {
        //noop
    }
}

private void loadOpener() {
    OpenerFragment openerFragment = OpenerFragment.newInstance();
    loadFragment(R.id.frame_fragment_container, openerFragment, true);
}

loadFragment() 负责处理事务和提交片段...

这是我的测试类:

@RunWith(AndroidJUnit4.class)
@LargeTest
public class LoginScreenTest {


@Rule
public ActivityTestRule<LoginActivity> mNotesActivityTestRule =
        new ActivityTestRule<>(LoginActivity.class);


@Test
public void clickAddNoteButton_opensAddNoteUi() throws Exception {
    onView(withId(R.id.button_login_submit)).perform(click());
    onView(withId(R.id.text_login)).check(matches(isDisplayed()));
}

在测试类中,如何确定应该显示哪个Fragment?

1个回答

9

实例化你的规则以防止自动启动活动:

    @Rule
    public ActivityTestRule<LoginActivity> mNotesActivityTestRule =
        new ActivityTestRule<>(LoginActivity.class, false, false);

然后手动启动您的活动并传入您感兴趣的意图:

Intent intent = new Intent();
intent.setAction(MainIntentService.ACTION_TARGET_OPENER);
mNotesActivityTestRule.launchActivity(intent);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接