我正在尝试测试GridView以确保它正在使用Robolectric加载图像。即使适配器中有数据,GridView.getChildAt(0)
也会返回null。我知道这是因为getChildAt()
根据屏幕上显示的内容返回。
有没有办法让这个测试在Robolectric中运行,还是我必须转到设备上进行测试(例如使用Espresso)?
@RunWith(RobolectricTestRunner.class)
@Config(manifest = "../../src/main/AndroidManifest.xml", emulateSdk = 18, reportSdk = 18)
public class ImageGridFragmentTest {
private ImageGridFragment mImageGridFragment;
@Before
public void setup() {
ShadowLog.stream = System.out;
mImageGridFragment = new ImageGridFragment();
startFragment(mImageGridFragment);
}
@Test
public void testImageGridFragmentLoaded() throws Exception {
assertNotNull(mImageGridFragment);
}
@Test
public void shouldLoadImageToGrid() throws Exception {
GridView gridView = (GridView) mImageGridFragment.getView().findViewById(R.id.gv_image_grid);
Log.d("gridView.size", Integer.toString(gridView.getCount()));
assertEquals(0, gridView.getFirstVisiblePosition());
View itemView = (View) gridView.getChildAt(0);
assertNotNull(itemView); // Test fails here
ImageView imageView = (ImageView) itemView.findViewById(R.id.iv_loaded_image);
ShadowDrawable shadowDrawable = Robolectric.shadowOf(imageView.getDrawable());
assertEquals(R.drawable.sample_image, shadowDrawable.getCreatedFromResId());
}
}
答案 0 :(得分:0)
这不是对系统进行彻底测试,但可能是最好的。
@Test
public void shouldLoadImageToGrid() throws Exception {
GridView gridView = (GridView) mImageGridFragment.getView().findViewById(R.id.gv_image_grid);
ImageGridData data = (ImageGridData) gridView.getAdapter().getItem(0);
assertEquals((long)R.drawable.sample_image, (long)data.getImageId());
}