【问题标题】:How to adjust the screen density for a Robolectric test?如何调整 Robolectric 测试的屏幕密度?
【发布时间】:2017-06-09 12:37:16
【问题描述】:

我目前正在我的应用中测试一个片段方法,该方法对运行它的设备的 DisplayMetrics 设置很敏感。您如何在 Robolectric 测试中为 RobolectricTestRunner 调整 DisplayMetrics(如果可能,请提供示例)?

这是我希望能够控制屏幕的 DisplayMetrics 的简单测试的要点。

    @Test
public void whenMyFramentMethod_willWorkForDensity() {

    ...

    startFragment(fragment);

    //Results of this method will vary with different screen sizes.
    Assert.assertEquals(200, fragment.fetchAWidth());
}

【问题讨论】:

  • 为什么要测试宽度?如果失败了怎么办?
  • 这个测试的有用部分是确保某些方法在测量某些东西时考虑了屏幕密度。确保发生这种情况的一个明显方法是将屏幕密度设置为特定的值,并验证该方法的结果是否乘以该因子。

标签: android unit-testing junit4 robolectric


【解决方案1】:

您现在应该使用 @Config 注释来设置环境:

@Config(qualifiers = "xhdpi")

【讨论】:

    【解决方案2】:

    您可以在ShadowResources上更改它:

    @Test
    public void shadow_resources_example(){
        final Context context = RuntimeEnvironment.application;
        final ShadowResources shadowResources = Shadows.shadowOf(context.getResources());
        shadowResources.setDensity(2f); //2 == xhdpi for example
        assertEquals(20, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, context.getResources().getDisplayMetrics()));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-24
      相关资源
      最近更新 更多