android-layout - 为什么在 Robolectric 中内容 View 的高度和宽度为零?

标签 android-layout robolectric activity-lifecycle

这是一个失败的测试:

@RunWith(RobolectricTestRunner.class)
public class FailTest {

    @Test
    public void heightAndWidth_shouldNotBeZero() {
        TestActivity testActivity = Robolectric.buildActivity(TestActivity.class).create().resume().visible().get();
        View contentView = testActivity.findViewById(69);
        Assertions.assertThat(contentView.getWidth()).isNotZero();
        Assertions.assertThat(contentView.getHeight()).isNotZero();
    }

    private static class TestActivity extends Activity {
        @Override protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            LinearLayout contentView = new LinearLayout(this);
            contentView.setId(69);
            contentView.setLayoutParams(new LayoutParams(666, 666));
            setContentView(contentView);
        }
    }
}

如您所见,我在 ActivityControllerdriving the Activity lifecycle 上调用了 visible() 方法。正确的方法。引用文档:

Wait, What's This visible() Nonsense?

Turns out that in a real Android app, the view hierarchy of an Activity is not attached to the Window until sometime after onCreate() is called. Until this happens, the Activity's views do not report as visible. This means you can't click on them (amongst other unexpected behavior). The Activity's hierarchy is attached to the Window on a device or emulator after onPostResume() on the Activity. Rather than make assumptions about when the visibility should be updated, Robolectric puts the power in the developer's hands when writing tests.

So when do you call it? Whenever you're interacting with the views inside the Activity. Methods like Robolectric.clickOn() require that the view is visible and properly attached in order to function. You should call visible() after create().

似乎我正在做我需要做的一切。那为什么我没有高度/宽度?​​

最佳答案

Robolectric 中没有布局 channel ,因此 View 尺寸始终为零。

https://github.com/robolectric/robolectric/issues/819

关于android-layout - 为什么在 Robolectric 中内容 View 的高度和宽度为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19829469/

相关文章:

java - ListView 中的评级栏样式,奇怪的行为

java - Android Studio 1.1.0 + Robolectric 2.4 导致 java.lang.annotation.AnnotationFormatError

android - Activity 生命周期困惑

android - IntelliJ 是否将 "test file"与 APK 中的应用程序一起打包

android - 使用 Robolectric 测试自定义 View

android - 如果 onPause() 或 onStop() 使用 Firebase 数据库中的嵌套回调中断函数,会发生什么

安卓 : How to detect app killed from recent apps list?

java - 将 ViewGroup 捕获到图像文件中

android - Android 中的左侧导航栏

java - 具有单项选择的自定义 ListView