getActivity() returns a null in my ActivityInstrumentationTestCase2 class

旧巷老猫 提交于 2019-12-05 11:29:31

If you are using ActivityInstrumentationTestCase2, you don't need the @Before, @Test annotations.

There are 2 ways to go:

  1. Continue to use ActivityInstrumentationTestCase2 to test this Activity, remove all the @Before @Test annotations from your code, and the test case should run without a problem.
  2. Don't subclass ActivityInstrumentationTestCase2, instead, to use AndroidJUnitRunner, and set the Activity by setting the activity test rule like this

Test case under JUnit4:

public class DraftsActivityTest2 {

@Rule
public ActivityTestRule<DraftsActivity> mActivityRule = new ActivityTestRule<>(
        DraftsActivity.class);

@Before
public void setUp(){
    DraftsActivity activity = mActivityRule.getActivity();
    ...}
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!