【问题标题】:How to mock the Resources class in android unit test in order to get the scaledDensity?如何在 android 单元测试中模拟 Resources 类以获得 scaledDensity?
【发布时间】:2017-01-18 11:54:23
【问题描述】:

我在我的 android 项目中使用此语句“ResourceResources.getSystem().getDisplayMetrics().scaledDensity”以获得缩放密度。当我编写单元测试时,它说应该模拟资源类。但是当我尝试模拟时,android 向我抛出了一个错误,资源中的 getSystem() 方法没有被模拟。

【问题讨论】:

标签: android mocking mockito robolectric


【解决方案1】:

来不及回答,但我会留在这里:)

我这样做是为了

Resources.getSystem().getStrings();

我认为这可以适应具体情况

ResourceResources.getSystem().getDisplayMetrics().scaledDensity

我也被这件事困扰了,我这样做了希望它有所帮助

 PowerMockito.mockStatic(Resources.class,RETURNS_MOCKS);
 Resources res=Mockito.mock(Resources.getSystem().getClass());
 PowerMockito.when(Resources.getSystem()).thenReturn(res);
 Mockito.when(res.getString(Mockito.anyInt())).thenReturn("any_message");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-07
    • 1970-01-01
    • 1970-01-01
    • 2016-04-04
    • 2017-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多