gpt4 book ai didi

android - 使用 Robolectric : Width and height are always 0 测试自定义 View

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:08:35 31 4
gpt4 key购买 nike

我已经为绘图应用构建了一个自定义 View (DrawView)。它在很大程度上取决于内部位图的实际宽度和高度。当我尝试使用 Robolectric 2.2 对其进行测试时, View 的长度和宽度均为 0,这使我的内部逻辑崩溃。我怎样才能模拟真实的屏幕尺寸?我使用一个简单的 LinearLayout 和 DrawView 作为其中唯一要测试的元素。这是我的布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/drawViewLayout">
<net.thoster.scribmasterlib.DrawView
android:id="@+id/drawView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>

这是我的单元测试:

@RunWith(RobolectricTestRunner.class)
public class DrawViewTest {
Activity activity;
DrawView drawView;
LinearLayout layout;

@Before
public void setUp() throws Exception {

ActivityController<Activity> activityController = Robolectric.buildActivity(Activity.class).create().start().resume()
.visible();

Activity activity = activityController.get();

layout = (LinearLayout) LayoutInflater.from(activity).inflate(R.layout.test, null);
drawView = (DrawView) layout.findViewById(R.id.drawView);

}

@Test
public void testFloodFill() throws Exception {
System.out.println(drawView.getWidth());
drawView.floodFill(new Point(1, 1), Color.BLACK, FloodFillMode.PIXEL);
Bitmap b = drawView.getDrawingAsNewBitmap();
int pixel = b.getPixel(2, 2);
assertEquals(pixel, Color.BLACK);

}

}

最佳答案

正如 erd 在 https://github.com/robolectric/robolectric/issues/819 中指出的那样...

Robolectric isn't trying to emulate Android - just fake enough of it so you can write reasonable unit tests. It doesn't surprise me that views don't have a width or height, since we're not doing anything that would cause a layout pass to happen.

请查看潜在变通方法的错误。

关于android - 使用 Robolectric : Width and height are always 0 测试自定义 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22200095/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com