2015-11-20 2 views
7

Привет, Я создаю простой адаптер RecycleView и пытаюсь протестировать все методы адаптера, но onCreateViewHolder для меня был плохим.Как отремонтировать эту строку LayoutInflater.from() в android

@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); 
} 

Пытаюсь с помощью Mockito построить макет класса ViewGroup и вернуть шпион в MockContext когда getContext() является вызовом, но это, кажется, что из-за меня, возвращающей MockContext LayoutInflater.from() возвращает исключение нулевого указателя.

Это мой тест

@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); 
} 

Спасибо заранее.

+1

У вас был ответ на этот вопрос? – GoCrazy

+1

Нет, мой друг, в конце концов, компания решила протестировать эту функциональность в качестве интеграционного теста –

ответ

1

Я столкнулся с этим вопросом, когда у меня была та же проблема. Я решил это решить сам.

Предположим, что у вас есть простой onCreateViewHolder вроде этого:

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

Используйте PowerMock издеваться статический экземпляр LayoutInflater. В приведенном ниже фрагменте я аннотировал с использованием пронумерованных комментариев все шаги, которые вам нужно предпринять, чтобы сделать эту работу:

import android.test.mock.MockContext; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 

import org.junit.Before; 
import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.mockito.Mock; 
import org.mockito.MockitoAnnotations; 
import org.powermock.core.classloader.annotations.PrepareForTest; 
import org.powermock.modules.junit4.PowerMockRunner; 

import static junit.framework.Assert.assertEquals; 
import static junit.framework.Assert.assertNotNull; 
import static org.mockito.Matchers.anyInt; 
import static org.mockito.Matchers.eq; 
import static org.mockito.Mockito.when; 
import static org.powermock.api.mockito.PowerMockito.mockStatic; 

// 1. signal JUnit to run this test PowerMockRunner 
@RunWith(PowerMockRunner.class) 

// 2. signal PowerMock to prepare the static instance of LayoutInflater for testing 
@PrepareForTest({LayoutInflater.class}) 
public class NewsRecyclerViewAdapterTest { 

    // 3. LayoutInflater.from(context) returns an inflater, 
    // so we need to mock that one 
    @Mock 
    LayoutInflater mockInflater; 

    @Mock 
    View mockView; 

    @Mock 
    ViewGroup mockParent; 

    private int dummyTestId; 

    private MockContext mockContext; 

    private NewsRecyclerViewAdapter adapter; 

    @Before 
    public void setUp() throws Exception { 

     MockitoAnnotations.initMocks(this); 

     dummyTestId = 0x10000; 

     // 4. mock the static LayoutInflater in "LayoutInflater.from()" 
     // so that we can ask it to return a mockInflater that we moked above 
     mockStatic(LayoutInflater.class); 

     mockContext = new MockContext(); 

     adapter = new NewsRecyclerViewAdapter(Arrays.asList(new NewsItem(), new NewsItem(), new NewsItem())); 
    } 

    @Test 
    public void onCreateViewHolderShouldReturnAValidViewHolder() throws Exception { 

     // 5. mock the context that comes from parent ViewGroup 
     when(mockParent.getContext()).thenReturn(mockContext); 

     // 6. mock the inflater that is returned by LayoutInflater.from() 
     when(LayoutInflater.from(mockContext)).thenReturn(mockInflater); 

     // 7. pass anyInt() as a resource id to care of R.layout.fragment_news_view_holder in onCreateViewHolder() 
     when(mockInflater.inflate(anyInt(), eq(mockParent), eq(false))).thenReturn(mockView); 

     // call onCreateViewHolder() to act 
     NewsViewHolder viewHolder = adapter.onCreateViewHolder(mockParent, dummyTestId); 

     // OKAY straightfoward right? 
     assertNotNull(viewHolder); 

     // this is not very important but I recommend it, 
     // it just returns the view sent to NewsViewHolder 
     // and verify it against the mockView that you inflated above 
     assertEquals(viewHolder.getItemView(), mockView); 
    } 

} 
Смежные вопросы