我刚刚开始,junit
我遇到的第一个问题是,我应该如何测试片段?
正在测试的活动有 1 个片段,这是主要布局。
@Override
protected void setUp() throws Exception {
super.setUp();
Intent intent = new Intent(getInstrumentation().getTargetContext(),
ActivityWelcome.class);
startActivity(intent, null, null);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
mFragmentWelcome = (FragmentWelcome) fragmentManager.findFragmentByTag(FragmentWelcome.TAG);
if (mFragmentWelcome == null) {
mFragmentWelcome= FragmentWelcome.newInstance();
fragmentManager
.beginTransaction()
.replace(android.R.id.content, mFragmentWelcome, FragmentWelcome.TAG)
.commit();
}
}
然后我继续测试布局:
@SmallTest
public void testLayout() {
ImageButton buttonImage = (ImageButton) getActivity().findViewById(my.package.R.id.button_invites);
assertNotNull(buttonImage);
assertEquals("ImageButton Invite has an invalid drawable"
, getActivity().getResources().getDrawable(my.package.R.drawable.light_social_invite)
, buttonImage);
}
错误:
java.lang.NullPointerException
at my.package.test.ActivityWelcomeUnitTest.testLayout(ActivityWelcomeUnitTest.java:55)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:214)
at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:199)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:545)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1551)
它失败了:
ImageButton buttonImage = (ImageButton) mFragmentWelcome.getView().findViewById(my.package.R.id.button_invites);
我不确定为什么片段为空,我显然执行此操作不正确,有人可以赐教吗?