How do I write an android JUnit test when my activity relies on extras passed through an Intent?

淺唱寂寞╮ 提交于 2019-12-05 00:14:34

The class you inherit, ActivityInstrumentationTestCase2, allows you to mock Intents. From the documentation:

You can inject custom Intents into your Activity (see setActivityIntent(Intent)).

The documentation for setActivityIntent() further clarifies:

Call this method before the first call to getActivity() to inject a customized Intent into the Activity under test.

If you do not call this, the default intent will be provided. If you call this after your Activity has been started, it will have no effect.

So you should be able to place a call to this method inside your setUp() before your call to getActivity(). You can pass in a mocked Intent into setActivityIntent like you mentioned -- just build a fake Intent with extras that you'd expect the Activity to see.

OK, I figured out my mistake! The code for setUp was just in the wrong order. It should look like:

@Override
public void setUp() {
    Intent addEvent = new Intent();
    addEvent.setClassName("com.UI", "com.UI.AddClassEvent");
    addEvent.putExtra("CourseNum", "60-415");
    setActivityIntent(addEvent);
    context = new RenamingDelegatingContext(getActivity(), "test_");
    model = new StudentDBModel(context);
}

I was calling getActivity() twice and the first call was ahead of the Intent. By using the correct order, the test runs fine. Thanks for the help McStretch.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!