这是一个失败的测试:
@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);
}
}
}
如您所见,我在 ActivityController
和 driving 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 theWindow
until sometime afteronCreate()
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 afteronPostResume()
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 callvisible()
aftercreate()
.
似乎我正在做我需要做的一切。那为什么我没有高度/宽度?
最佳答案
Robolectric 中没有布局 channel ,因此 View 尺寸始终为零。
关于android-layout - 为什么在 Robolectric 中内容 View 的高度和宽度为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19829469/