【问题标题】:Layout Inflater Mock issue布局充气机模拟问题
【发布时间】:2018-08-13 05:52:51
【问题描述】:

我正在尝试使用layourInflater 测试一个方法,但我在该行得到一个空指针

when(LayoutInflater.from(context)).thenReturn(layoutInflaterMock);

我尝试测试的方法如下所示:

publc View method(RoomInfoAdapter.FacilityRoomInfoViewHolder holder) {

        View linearLayout = LayoutInflater.from(context).inflate(R.layout.some, holder.getParentLayout(), false);
        TextView label = linearLayout.findViewById(R.id.label);
        TextView textView = linearLayout.findViewById(R.id.type_value);
....
}

还有我的测试课:

@RunWith(RobolectricTestRunner.class)
@PrepareForTest({LayoutInflater.class})
@Config(sdk = 23, manifest = "src/main/AndroidManifest.xml")
public class Test {

    @Mock
    private Context context;

    @Mock
    private LayoutInflater layoutInflaterMock;

@Before
    public void setup() throws Exception {
        MockitoAnnotations.initMocks(this);
        context = RuntimeEnvironment.application;
....
    }

@Test
    public void test() {

        when(LayoutInflater.from(context)).thenReturn(layoutInflaterMock);
   ....
    }

我试图遵循这个答案: How to unit test this line of LayoutInflater.from() in android

但它不起作用。

编辑:现在我得到:

org.mockito.exceptions.misusing.MissingMethodInvocationException: when() 需要一个参数,该参数必须是“模拟方法调用”。 例如: when(mock.getArticles()).thenReturn(articles);

甚至可以使用 mockito 和 robolectric 来做 when(LayoutInflater.from(context)).thenReturn(... 吗?

【问题讨论】:

  • 看起来你需要 power mockito 然后模拟静态类

标签: java android unit-testing mockito robolectric


【解决方案1】:

要模拟静态方法或类,您必须使用 PowerMock,并且将其与 Robolectric 一起使用有点棘手。

您可以在这里尝试: https://github.com/robolectric/robolectric/wiki/Using-PowerMock

【讨论】:

    猜你喜欢
    • 2015-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    相关资源
    最近更新 更多