vendredi 20 novembre 2015

How to unit test this line of LayoutInflater.from() in android

Hi Am building a simple RecycleView Adapter and am trying to test all the methods of the adapter but the onCreateViewHolder is been dificult for me.

 @Override
public NewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_news,parent,false);
return new NewsViewHolder(v);
}

I Try using mockito to build a mock of the viewGroup class and return a spy of the MockContext when getContext() is call but it seems to be that because am returning a MockContext LayoutInflater.from() return a null pointer exception.

This is my test

 @Test
public void testOnCreateViewHolder() throws Exception {
    ViewGroup vg = mock(ViewGroup.class);
    MockContext mockContext = new MockContext();
    MockContext spyContext = spy(mockContext);
    when(vg.getContext()).thenReturn(spyContext);


    NewsViewHolder vh = adapter.onCreateViewHolder(vg, 0);
    Assert.assertNotNull("Response cant be null",vh);
}

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire